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

前端 未结 3 1432
有刺的猬
有刺的猬 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: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

提交回复
热议问题