将小数转换为十六进制

时间:2018-02-26 17:17:44

标签: c# .net

我想将小数转换为十六进制:

string hex = IntToString(dezimal,
             new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                          'A', 'B', 'C', 'D', 'E', 'F'});
textBoxHexa.Text = hex;

但是我收到了一个错误:

  

输入字符串的格式不正确

这是最好的方法吗?如果没有,有什么更好的方法?

1 个答案:

答案 0 :(得分:-1)

Decimals can't be represented directly by hexadecimal, there's no floating point, for that you need a representation of the floating point number, the most common is the IEEE-754 representation which uses the actual processors.

In case you want that representation you can do this (using unsafe):

decimal m = 3.4353M;
byte* data = (byte*)&m;

string hex = "";

for(int buc = 0; buc < 16; buc++)
    hex += data[buc].ToString("X2");

//Result: 00000400000000003186000000000000