2011-02-28 6 views
2

내 응용 프로그램의 일부를 C++에서 C#으로 변환했습니다. 어쨌든 C#에 해당하는 (다른 유형의 변수 읽기)

uint result = 0; 

... // a value is set to result 

return (*((float *)&result)); // get result as a float value 

가 C 번호에 마지막 줄을 변환 :이 인코딩/디코딩 내가 UINT로 정의 float로서 변수를 읽을 필요 부분이있다? 모두에게 감사드립니다.

+0

만약 내가이 질문을 오해하지 않았다면, C#에서'return Convert.ToSingle (result); '처럼 할 수 있습니다. –

답변

6

당신은 안전하지 않은 코드로 그렇게 할 수 있습니다. 안전하지 않은 코드를 사용할 수없는 상황에 처한 경우 효과가 떨어집니다.

편집 : (당신은 할 수

[StructLayout(LayoutKind.Explicit)] 
    struct Int32SingleUnion 
{ 
    [FieldOffset(0)] 
    int i; 

    [FieldOffset(0)] 
    float f; 

    internal Int32SingleUnion(int i) 
    { 
     this.f = 0; // Just to keep the compiler happy 
     this.i = i; 
    } 

    internal Int32SingleUnion(float f) 
    { 
     this.i = 0; // Just to keep the compiler happy 
     this.f = f; 
    } 

    internal int AsInt32 
    { 
     get { return i; } 
    } 

    internal float AsSingle 
    { 
     get { return f; } 
    } 
} 

:이 내가 MiscUtil에 사용했던 또 다른 대안은 원래의 예처럼 더 많은 일을하기 위해 C 같은 "노동 조합"을 사용하지만 사용자 정의 구조체를 통해 길고 두 배로 똑같이하십시오.)

4

BitConverter을 사용할 수 있습니다. 또는 바이트 배열로 값을 변환 할 BitConverter.GetBytes()를 사용할 수있는 다음 BitConverter.ToSingle() 다시 변환 - 예를 들어,

return BitConverter.ToSingle(BitConverter.GetBytes(result), 0); 
2

두 가지 옵션 :

1)를 사용하여 C#을 포인터. 컴파일러는 프로젝트 속성에서 "안전하지 않은 코드"를 활성화하면 사용자를 허용합니다. 자세한 내용을 보려면 http://msdn.microsoft.com/en-us/library/y31yhkeb(v=VS.100).aspx

2) BitConverter 클래스를 사용하십시오. 특히 BitConverter.GetBytes()는 사용자의 uint를 바이트로 변환 한 다음 BitConverter.ToSingle()을 사용하여 바이트를 float로 변환합니다. 여기에 읽으십시오 : http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx

행운을 빕니다!

관련 문제