我一直在将应用程序的某些部分从 C++ 转换为 C#。有这个编码/解码部分,我需要将变量读取为定义为 uint 的 float :
uint result = 0;
... // a value is set to result
return (*((float *)&result)); // get result as a float value
无论如何要将最后一行转换为 C#?谢谢大家。。
最佳答案
您可以使用不安全的代码来做到这一点 - 或者您可以使用 BitConverter.GetBytes()
将值转换为字节数组,然后使用 BitConverter.ToSingle()
转换回来。显然,这效率较低,但如果您处于无法使用不安全代码的情况下,它会起作用。
编辑:我在 MiscUtil 中使用了另一种选择,使用类似 C 的“union ”来更像您的原始示例,但通过自定义结构:
[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; }
}
}
(当然,你可以对 long 和 double 做同样的事情。)
关于C# 等效于(将变量读取为不同类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5139910/