实现一个使用 PHP and/or JavaScript 交换 32 位整数 "byte-wise" 的函数

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

我是一名前端开发人员,经常使用 JavaScript/PHP。如果有人能给我解决方案并帮助我解释它(如果不是很耗时的话),我将不胜感激。

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

byte_swap(0x12345678)

// Expected output
0x78563412

我在网上阅读了有关“屏蔽和移位策略”的信息,但无法理解:(我在 JS/PHP 中也找不到该策略的解决方案。

如果有比“mask and shift strategy”更好的策略,我也想一探究竟。

非常感谢您的帮助。

这里是示例代码,它首先将每个字节提取到单独的变量中,然后重新构造 32 位整数

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));