Nodejs中的十六进制到二进制

时间:2017-08-02 09:14:13

标签: node.js binary hex

我在nodejs Tcp Client

中有这个十六进制
82380000000000000400000000000000

我使用了parseint函数将其转换为

1.73090408076117e+38

但我需要得到它的二进制表示

10000010001110000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000

我可以从上面的十六进制格式获得这个二进制表示吗?

3 个答案:

答案 0 :(得分:0)

使用toString将基数指定为参数即可。例如,如果要在将其解析为整数后将其转换为二进制字符串:

var number = '82380000000000000400000000000000';
console.log(parseInt(number).toString(2));

如果需要十六进制字符串,只需使用 .toString(16);

如果您不想用数字解析字符串:

var number = 82380000000000000400000000000000;
console.log(number.toString(2));

希望这会有所帮助。

答案 1 :(得分:0)

(function(){

    var ConvertBase = function (num) {
        return {
            from : function (baseFrom) {
                return {
                    to : function (baseTo) {
                        return parseInt(num, baseFrom).toString(baseTo);
                    }
                };
            }
        };
    };

    // binary to decimal
    ConvertBase.bin2dec = function (num) {
        return ConvertBase(num).from(2).to(10);
    };

    // binary to hexadecimal
    ConvertBase.bin2hex = function (num) {
        return ConvertBase(num).from(2).to(16);
    };

    // decimal to binary
    ConvertBase.dec2bin = function (num) {
        return ConvertBase(num).from(10).to(2);
    };

    // decimal to hexadecimal
    ConvertBase.dec2hex = function (num) {
        return ConvertBase(num).from(10).to(16);
    };

    // hexadecimal to binary
    ConvertBase.hex2bin = function (num) {
        return ConvertBase(num).from(16).to(2);
    };

    // hexadecimal to decimal
    ConvertBase.hex2dec = function (num) {
        return ConvertBase(num).from(16).to(10);
    };

    this.ConvertBase = ConvertBase;

})(this);

答案 2 :(得分:-1)

我使用下面的代码将十六进制映射到二进制字符串。

let x = '82380000000000000400000000000000'

function toBin(hexaString) {
  let mapping = {
        '0': '0000',
        '1': '0001',
        '2': '0010',
        '3': '0011',
        '4': '0100',
        '5': '0101',
        '6': '0110',
        '7': '0111',
        '8': '1000',
        '9': '1001',
        'a': '1010',
        'b': '1011',
        'c': '1100',
        'd': '1101',
        'e': '1110',
        'f': '1111',
        'A': '1010',
        'B': '1011',
        'C': '1100',
        'D': '1101',
        'E': '1110',
        'F': '1111',
    }
    let bitmaps = ''
    for (let i = 0; i < hexaString.length; i++) {
        bitmaps += mapping[hexaString[i]]
    }

    return bitmaps
}

console.log(toBin(x))

输出

10000010001110000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000