Convert a 32bit integer into 4 bytes of data in javascript

前端 未结 3 1422
有刺的猬
有刺的猬 2021-02-12 20:04

I was asked to convert the integers to 32-bit binary numbers. So is used integer.toString(2) and got the required value in 32-bit binary format of 0\'sand 1\'s. But

相关标签:
3条回答
  • 2021-02-12 20:13

    Now you can use ArrayBuffer and DataView. They are native so the performance will be much better if you need to use it very often.

    function toBytesInt32 (num) {
        arr = new ArrayBuffer(4); // an Int32 takes 4 bytes
        view = new DataView(arr);
        view.setUint32(0, num, false); // byteOffset = 0; litteEndian = false
        return arr;
    }
    

    equals to

    function toBytesInt32 (num) {
        arr = new Uint8Array([
             (num & 0xff000000) >> 24,
             (num & 0x00ff0000) >> 16,
             (num & 0x0000ff00) >> 8,
             (num & 0x000000ff)
        ]);
        return arr.buffer;
    }
    

    which use javascript bitwise operators to achieve that.

    0 讨论(0)
  • 2021-02-12 20:22

    if you need a hex format output, here is the code.

    /* Convert value as 8-bit unsigned integer to 2 digit hexadecimal number. */
    
    function hex8(val) {
        val &= 0xFF;
        var hex = val.toString(16).toUpperCase();
        return ("00" + hex).slice(-2);
    }
    
    /* Convert value as 16-bit unsigned integer to 4 digit hexadecimal number. */
    
    function hex16(val) {
        val &= 0xFFFF;
        var hex = val.toString(16).toUpperCase();
        return ("0000" + hex).slice(-4);
    }
    
    /* Convert value as 32-bit unsigned integer to 8 digit hexadecimal number. */
    
    function hex32(val) {
        val &= 0xFFFFFFFF;
        var hex = val.toString(16).toUpperCase();
        return ("00000000" + hex).slice(-8);
    }
    
    
    var num = 1065489844;
    console.log("0x" + hex32(num)); // will output 0x3F8215B4 
    
    0 讨论(0)
  • 2021-02-12 20:28

    SEIAROTg's answer does not output a string. I have theroughly tested with both positive and negative numbers and this code will give you a 4 byte string output representing the number in big endien format(2's compliment 0xFFFFFFFF = -1).

    var toBytesInt32=function(num) {
        var ascii='';
        for (let i=3;i>=0;i--) {
            ascii+=String.fromCharCode((num>>(8*i))&255);
        }
        return ascii;
    };
    

    by the way if you want to go the other way around you can use

    var fromBytesInt32=function(numString) {
        var result=0;
        for (let i=3;i>=0;i--) {
            result+=numString.charCodeAt(3-i)<<(8*i);
        }
        return result;
    };
    

    to convert a 4 byte string to an integer

    0 讨论(0)
提交回复
热议问题