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

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

提交回复
热议问题