【问题标题】:Convert a signed decimal to hex encoded with two's complement将有符号十进制转换为用二进制补码编码的十六进制
【发布时间】:2011-09-03 00:31:51
【问题描述】:

我需要通过二进制补码表示法将 signed 整数编码为十六进制。例如我想转换

e.g. -24375 to 0xffffa0c9.

到目前为止,我一直在研究以下几行:

parseInt(-24375).toString(2)
> "-101111100110111"    

这与 Wolfram Alpha displays 匹配,但我不确定如何获得数字的签名 24 位 int 表示 (ffffa0c9)。

我已经研究出如何获取无符号二进制数并将其表示为二进制补码:

~ parseInt("101111100110111", 2) + 1
> -23475

但我不确定要将此数字的二进制表示形式转换为十六进制。

有什么想法吗?

【问题讨论】:

    标签: javascript twos-complement


    【解决方案1】:

    为了创建固定大小的二进制恭维数,我创建了工厂方法:

     function createToInt(size) {
        if (size < 2) {
            throw new Error('Minimum size is 2');
        }
        else if (size > 64) {
            throw new Error('Maximum size is 64');
        }
    
        // Determine value range
        const maxValue = (1 << (size - 1)) - 1;
        const minValue = -maxValue - 1;
    
        return (value) => {
            if (value > maxValue || value < minValue) {
                throw new Error(`Int${size} overflow`);
            }
    
            if (value < 0) {
                return (1 << size) + value;
            }
            else {
                return value;
            }
        };
    }
    

    现在,为了解决您的问题,您可以创建函数toInt8toInt16toInt32 等。并用它来将 JS 数字转换为二进制的恭维。 int8 示例:

    const toInt8 = createToInt(8);
    
    '0x' + toInt8(-128).toString(16); // -> 0x80
    '0x' + toInt8(127).toString(16); // -> 0x7f
    '0x' + toInt8(-1).toString(16); // -> 0xff
    
    // Values less then 16 should be padded
    '0x' + toInt8(10).toString(16).padStart(2, '0); // -> 0x0a
    

    【讨论】:

      【解决方案2】:

      这是一个使用parseInt 的非常简单的解决方案:

      function DecimalHexTwosComplement(decimal) {
        var size = 8;
      
        if (decimal >= 0) {
          var hexadecimal = decimal.toString(16);
      
          while ((hexadecimal.length % size) != 0) {
            hexadecimal = "" + 0 + hexadecimal;
          }
      
          return hexadecimal;
        } else {
          var hexadecimal = Math.abs(decimal).toString(16);
          while ((hexadecimal.length % size) != 0) {
            hexadecimal = "" + 0 + hexadecimal;
          }
      
          var output = '';
          for (i = 0; i < hexadecimal.length; i++) {
            output += (0x0F - parseInt(hexadecimal[i], 16)).toString(16);
          }
      
          output = (0x01 + parseInt(output, 16)).toString(16);
          return output;
        }
      }
      

      对于长度不超过 16 的十六进制应该可以正常工作。

      【讨论】:

      • 这很好用
      猜你喜欢
      • 2014-04-16
      • 2014-03-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-21
      • 2013-09-28
      • 2016-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多