【问题标题】:How to convert float to uint by float representation?如何通过浮点表示将浮点转换为 uint?
【发布时间】:2014-02-15 17:42:52
【问题描述】:

C 中,我将这样做以将数字的浮点表示形式转换为 DWORD。从地址中获取值并将内容转换为 DWORD。

dwordVal = *(DWORD*)&floatVal;

例如,44.54321 将变为 0x42322C3F

我怎样才能在C# 中做同样的事情?

【问题讨论】:

  • 实际上*(DWORD*)&floatVal 在 C 中是错误的做法,因为它违反了 C 编译器用于优化的严格别名规则。正确的方法涉及联合(参见 C99tc3 脚注 82)或memcpy()

标签: c# floating-point int


【解决方案1】:

您可以使用BitConverter 类:

uint value = BitConverter.ToUInt32(BitConverter.GetBytes(44.54321F), 0);
Console.WriteLine("{0:x}", value); // 42322c3f

您也可以更直接地使用unsafe context

float floatVal = 44.54321F;
uint value;
unsafe { 
    value = *((uint*)(&floatVal));
}
Console.WriteLine("{0:x}", value); // 42322c3f

但是,我强烈建议避免这种情况。见Should you use pointers (unsafe code) in C#?

【讨论】:

    【解决方案2】:

    使用 BitConverter 类:

    float f = 44.54321f;
    uint u = BitConverter.ToUInt32(BitConverter.GetBytes(f), 0);
    System.Diagnostics.Debug.Assert(u == 0x42322C3F);
    

    【讨论】:

      【解决方案3】:

      bitconvert 在每次调用时都会创建一个新的字节数组。 这是解决方案:

          unsafe public static float ToDecibel(this float x)
          {
              uint* y = (uint*)&x;
              (*y) &= 0x7fffffff;
              return (*y) * 7.17711438e-7f - 764.6161886f;
          }
      

      【讨论】:

      • +1 用于记住 unsafe。但是......这改变了x!最好使用uint y = *(uint*)&x; y &= 0x7fffffff; return y * 7.17711438e-7f - 764.6161886f; 来避免更改x
      猜你喜欢
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多