简体   繁体   English

在C#中将double转换为hex

[英]Convert double into hex in C#

I have this value: 我有这个价值:

double headingAngle = 135.34375;

I would like to convert it to HEX and print the HEX to the console. 我想将其转换为HEX并将HEX打印到控制台。 I have already converted a string and int into their respective HEX values, but a double seems to be much more tricky. 我已经将一个字符串和int转换为它们各自的HEX值,但是双精度似乎要复杂得多。 Can someone point me in the right direction? 有人能指出我正确的方向吗?

Well, I googled for a minute or two and according to this here is a quite ellegant solution 好吧,我用谷歌搜索了一两分钟,据此, 是一个非常优雅的解决方案

    double d = 12.09;
    Console.WriteLine("Double value: " + d.ToString());
    byte[] bytes = BitConverter.GetBytes(d);
    Console.WriteLine("Byte array value:");
    Console.WriteLine(BitConverter.ToString(bytes));

You can convert base 10 to base 16 by continually multiplying the fraction by 16, stripping out the 'whole' number, and repeating with the remainder. 您可以通过将分数连续乘以16,将基数10转换为基数16,去掉“整数”,然后重复余数。

So to convert 0.1 Decimal to Hex 所以要将0.1 Decimal转换为Hex

0.1 * 16
= 1.6

So 1 becomes the first hex value. 所以1成为第一个十六进制值。 Keep going with the remaining 0.6 继续使用剩下的0.6

0.6 * 16 = 9.6

So 9 becomes the second hex value. 所以9成为第二个十六进制值。 Keeping going with the remaining 0.6 保持剩下的0.6

0.6 * 16 = 9.6

etc. 等等

So 0.1 Decimal = 0.19999 .. recurring hex 所以0.1 Decimal = 0.19999 ..重复出现的十六进制

From memory this works for any radix. 从内存中,这适用于任何基数。 Obviously in hex a whole value of 10 would be A etc. 显然,在十六进制中,整数值为10将是A等。

Assuming you want to convert to hexadecimal base/radix, the following should do the trick: 假设您要转换为十六进制基数/基数,以下应该可以做到:

static void Main(string[] args)
{
    Console.WriteLine(Base16(135.34375, 10));
    Console.ReadLine();
}

private static string Base16(double number, int fractionalDigits)
{
    return Base(number, fractionalDigits, new char[]{
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        'A', 'B', 'C', 'D', 'E', 'F' });
}

private static string Base(double number, int fractionalDigits, params char[] characters)
{
    int radix = characters.Length;
    StringBuilder sb = new StringBuilder();

    // The 'whole' part of the number.
    long whole = (long)Math.Floor(number);
    while (whole > 1)
    {
        sb.Insert(0, characters[whole % radix]);
        whole = whole / radix;
    }

    // The fractional part of the number.
    double remainder = number % 1;
    if (remainder > Double.Epsilon || remainder < -Double.Epsilon)
    {
        sb.Append('.');

        double nv;
        for (int i = 0; i < fractionalDigits; i++)
        {
            nv = remainder * radix;
            if (remainder < Double.Epsilon && remainder > -Double.Epsilon)
                break;
            sb.Append(characters[(int)Math.Floor(nv)]);
            remainder = nv % 1;
        }
    }

    return sb.ToString();
}

The hexadecimal conversion of 135.34375 is 87.58 . 135.34375的十六进制转换率为87.58

BitConverter.DoubleToInt64Bits(value).ToString("X")

Try this: 试试这个:

public static string Format(double number, double @base)
{
    StringBuilder format = new StringBuilder();
    if(number < 0)
    {
        format.Append('-');
        number = -number;
    }
    double log = Math.Log(number, @base);
    bool frac = false;
    double order;
    if(log < 0)
    {
        frac = true;
        format.Append(digits[0]);
        format.Append('.');
        order = 1/@base;
    }else{
        order = Math.Pow(@base, Math.Floor(log));
    }
    while(number != 0 || order >= 1)
    {
        double digit = Math.Floor(number/order);
        if(digit >= @base) break;
        number = number-digit*order;
        number = Math.Round(number, 15);
        if(order < 1 && !frac)
        {
            format.Append('.');
            frac = true;
        }
        order /= @base;
        if(digit >= 10)
        {
            format.Append((char)('A'+(digit-10)));
        }else{
            format.Append((char)('0'+digit));
        }
    }
    return format.ToString();
}

Use it like Format(headingAngle, 16) . Format(headingAngle, 16)一样使用它。 You can also comment out number = Math.Round(number, 15); 你也可以注释掉number = Math.Round(number, 15); for more interesting results. 更有趣的结果。

Result is in culture-invariant format. 结果是文化不变的格式。 For 135.34375, it returns 87.58. 对于135.34375,它返回87.58。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM