2014-09-26 142 views
-1

我有这样的代码是十六进制转换浮动基本上,我需要这个操作转换IEEE 754浮点数以十六进制字符串

byte[] bytes = BitConverter.GetBytes(0x445F4002); 
float myFloat = BitConverter.ToSingle(bytes, 0); 
MessageBox.Show(myFloat.ToString()); 

我想进入浮动和把它转化为十六进制字符串的反向。

+0

这里的答案是893.0001 – ex0ff 2014-09-26 16:35:39

回答

3
  1. 拨打BitConverter.GetBytes获得一个表示您的浮点数的字节数组。
  2. 字节数组转换为十六进制字符串:How do you convert Byte Array to Hexadecimal String, and vice versa?

FWIW,在你的问题的代码不会做这种相反。事实上,您问题中的代码不会收到十六进制字符串。它接收一个你用十六进制表示的整型文字。如果你想从一个十六进制字符串转换为一个浮点数,那么你可以使用上面链接中的代码将十六进制字符串转换为字节数组。然后你将该字节数组传递给BitConverter.ToSingle


看来你有问题把它放在一起。这个函数,从我上面的链接的问题采取从字节数组转换为十六进制字符串:

public static string ByteArrayToString(byte[] ba) 
{ 
    StringBuilder hex = new StringBuilder(ba.Length * 2); 
    foreach (byte b in ba) 
    hex.AppendFormat("{0:x2}", b); 
    return hex.ToString(); 
} 

这样称呼它:

string hex = ByteArrayToString(BitConverter.GetBytes(myfloat)); 

而且在评论你的状态,你想以反转字节。你可以找到如何做到这一点:How to reverse the order of a byte array in c#?

+0

不,我需要将浮点数转换为十六进制 – ex0ff 2014-09-26 16:46:13

+0

我知道。从问题标题中可以清楚地看出。你只需要按照我的答案中的步骤。 – 2014-09-26 16:47:26

+0

请问你给我看一段适用于你的答案的代码,我不是很好处理字节 – ex0ff 2014-09-26 16:49:40

相关问题