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

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

提交回复
热议问题