将DWORD转换为浮点数,将浮点数转换为DWORD

huangapple go评论61阅读模式
英文:

Convert DWORD to float and float to DWORD

问题

我从浮点数到DWORD的转换结果如下:

float f = 2.4f;
Uint32 value = BitConverter.ToUInt32(BitConverter.GetBytes(f), 0);
Console.WriteLine("{0:D}", value); // 1075419546

我想要从DWORD,1075419546,转换成浮点数,2.4f。我该如何实现这个转换?

英文:

I got the conversion result from float to DWORD like below.

float f = 2.4f;
Uint32 value = BitConverter.ToUInt32(BitConverter.GetBytes(f), 0);
Console.WriteLine("{0:D}", value); // 1075419546

And I would like to get conversion from DWORD,1075419546 to float,2.4f.
How can I get this?

答案1

得分: 1

Finally, I made it. Please refer to below if you need.

UInt32 value = 1075419546;

string hexString = value.ToString("X8");

byte[] floatBytes = Enumerable.Range(0, hexString.Length).Where(x => x % 2 == 0).Select(x => Convert.ToByte(hexString.Substring(x, 2), 16)).ToArray();

Array.Reverse(floatBytes);

float floatValue = BitConverter.ToSingle(floatBytes, 0);
Console.WriteLine("{0:F}", floatValue);

英文:

Finally, I made it. Please refer to below if you need.

UInt32 value = 1075419546;

string hexString = value.ToString("X8");

byte[] floatBytes = Enumerable.Range(0, hexString.Length).Where(x => x % 2 == 0).Select(x => Convert.ToByte(hexString.Substring(x, 2), 16)).ToArray();

Array.Reverse(floatBytes);

float floatValue = BitConverter.ToSingle(floatBytes, 0);
Console.WriteLine("{0:F}", floatValue);   

huangapple
  • 本文由 发表于 2023年4月20日 09:42:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76059954.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定