如何将二进制数字转换为带符号的十进制数字 [英] How to convert a binary number into a Signed decimal number

查看:786
本文介绍了如何将二进制数字转换为带符号的十进制数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似这样的二进制数.var data ="1100110010". 我正在尝试将此转换为Javascript中适当的带符号十进制数.

I have a binary number something like this.. var data = "1100110010". I am trying to convert this into appropriate signed decimal number in Javascript.

我使用的步骤如下

1)var data = "1100110010"; var bin2dec = parseInt(data,2).toString(10);

1) var data = "1100110010"; var bin2dec = parseInt(data,2).toString(10);

bin2dec给出转换后的Decimal数字为"818".

The bin2dec gives the converted Decimal number as "818" .

但是我也想访问二进制数字的带符号十进制.

But I want to access the signed decimal of the binary number too.

此二进制代码的带符号十进制数字是"-206".

The signed decimal number for this binary code is "-206".

如何从给定的二进制数中访问带符号和无符号十进制值.请告诉我 .任何想法都会有所帮助

How can I access both signed and unsigned decimal Value from a given Binary Number. Please let me know . Any ideas would help

推荐答案

使用一些移位技巧

function uintToInt(uint, nbit) {
    nbit = +nbit || 32;
    if (nbit > 32) throw new RangeError('uintToInt only supports ints up to 32 bits');
    uint <<= 32 - nbit;
    uint >>= 32 - nbit;
    return uint;
}

uintToInt(818, 10); // -206

  • 为什么818?因为这是您的二进制字符串

    • Why 818? Because this is the uint value of your binary string

      parseInt('1100110010', 2); // 818
      

    • 为什么10?因为您的带符号int由二进制字符串

    • Why 10? Because your signed int is represented by 10 bits in your binary string

      '1100110010'.length; // 10
      

    • 请注意,对于正数,您不能仅使用nbit = str.length;,因为字符串可能未填充0,因此您需要知道您实际使用了多少位

      Please note that for positive numbers, you can't just take nbit = str.length; as the string may not be 0-padded, you'll need to know how many bits you're actually using

      您可能还想为uint > 4294967295

      出于完整性考虑,

      function intToUint(int, nbit) {
          var u = new Uint32Array(1);
          nbit = +nbit || 32;
          if (nbit > 32) throw new RangeError('intToUint only supports ints up to 32 bits');
          u[0] = int;
          if (nbit < 32) { // don't accidentally sign again
              int = Math.pow(2, nbit) - 1;
              return u[0] & int;
          } else {
              return u[0];
          }
      }
      
      intToUint(-206, 10); // 818
      

      这篇关于如何将二进制数字转换为带符号的十进制数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆