Search code examples
javascriptphpbytemaskswap

Implement a function that swaps a 32-bit integer "byte-wise" using PHP and/or JavaScript


I am a front-end developer and uses JavaScript/PHP a lot. I would appreciate if someone could give me the solution and help me explain it (if not very time consuming).

function byte_swap() {
   // implementation
   return 0;
}

byte_swap(0x12345678)

// Expected output
0x78563412

I read up online about "mask and shift strategy", but couldn't understand it :( I also couldn't find the solution with this strategy in JS/PHP.

If there are other better strategies than "mask and shift strategy", I would like to explore them as well.

Thanks a lot in advance for all the help.


Solution

  • here is sample code which first extracts each byte into separate variable and then reconstruct 32 bit integer back

    function byte_to_hex(b) {
       let s = b.toString(16);
       return b > 0xf ? s : "0" + s;
    }
    
    function byte_swap(t) {
       let a = t & 0xff;
       let b = (t >> 8) & 0xff;
       let c = (t >> 16) & 0xff;
       let d = (t >> 24) & 0xff;
       return byte_to_hex(a) + byte_to_hex(b) + byte_to_hex(c) + byte_to_hex(d);
    }
    
    console.log('0x' + byte_swap(0x12345678));
    console.log('0x' + byte_swap(0xFF85));