2014-09-26 144 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

相關問題