gpt4 book ai didi

algorithm - 如何将十进制分数转换为十六进制分数?

转载 作者:行者123 更新时间:2023-12-03 23:24:35 24 4
gpt4 key购买 nike

所以我在想,你如何将十进制分数转换为十六进制分数?
有哪些转换方法,是否有捷径?

最佳答案

您可以使用此算法:

  • 取数字的小数部分(即整数部分等于零)
  • 乘以 16
  • 将整数部分转换为十六进制并放下
  • 转到步骤 1

  • 例如,让我们找出 pi = 3.141592653589793 ...

    整数部分很明显 - 0x3 ;至于小数部分( 0.141592653589793 )我们有
      0.14159265358979 * 16 =  2.26548245743664; int part  2 (0x2); frac 0.26548245743664
    0.26548245743664 * 16 = 4.24771931898624; int part 4 (0x4); frac 0.24771931898624
    0.24771931898624 * 16 = 3.96350910377984; int part 3 (0x3); frac 0.96350910377984
    0.96350910377984 * 16 = 15.41614566047744; int part 15 (0xF); frac 0.41614566047744
    0.41614566047744 * 16 = 6.65833056763904; int part 6 (0x6); frac 0.65833056763904
    0.65833056763904 * 16 = 10.53328908222464; int part 10 (0xA); ...

    所以 pi(十六进制)= 3.243F6A ...

    可能的 (C#) 实现
    public static String ToHex(Double value) {
    StringBuilder Sb = new StringBuilder();

    if (value < 0) {
    Sb.Append('-');

    value = -value;
    }

    // I'm sure you know how to convert decimal integer to its hexadecimal representation
    BigInteger bi = (BigInteger) value;
    Sb.Append(bi.ToString("X"));

    value = value - (Double)bi;

    // We have integer value in fact (e.g. 5.0)
    if (value == 0)
    return Sb.ToString();

    Sb.Append('.');

    // Double is 8 byte and so has at most 16 hexadecimal values
    for (int i = 0; i < 16; ++i) {
    value = value * 16;
    int digit = (int) value;

    Sb.Append(digit.ToString("X"));

    value = value - digit;

    if (value == 0)
    break;
    }

    return Sb.ToString();
    }

    测试
       Console.Write(ToHex(Math.PI)); // <- returns "3.243F6A8885A3"

    关于algorithm - 如何将十进制分数转换为十六进制分数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20650954/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com