Eps*_*ime 17
直接的方法是执行8个掩码,8个旋转和7个添加:
$blah = $blah & 128 >> 7 + $blah & 64 >> 5 + $blah & 32 >> 3 + $blah & 16 >> 1 + $blah & 8 << 1 + $blah & 4 << 3 + $blah & 2 << 5 + $blah & 1 << 7;
Run Code Online (Sandbox Code Playgroud)
Pau*_*xon 16
查看Bit Twiddling Hacks中反转位序列的部分.应该很容易将其中一种技术改编成PHP.
尽管PHP可能不实用,但使用3个64位操作有一个特别迷人的:
unsigned char b; // reverse this (8-bit) byte
b = (b * 0x0202020202ULL & 0x010884422010ULL) % 1023;
Run Code Online (Sandbox Code Playgroud)
最快的方式,也是需要更多空间的方法是查找,其中一个字节的每个可能值(如果你去整个范围,则为256)与其"反向"等价物相关联.
如果你只有几个这样的字节来处理,逐位运算符会做,但会更慢,可能是这样的:
function reverseBits($in) {
$out = 0;
if ($in & 0x01) $out |= 0x80;
if ($in & 0x02) $out |= 0x40;
if ($in & 0x04) $out |= 0x20;
if ($in & 0x08) $out |= 0x10;
if ($in & 0x10) $out |= 0x08;
if ($in & 0x20) $out |= 0x04;
if ($in & 0x40) $out |= 0x02;
if ($in & 0x80) $out |= 0x01;
return $out;
}
Run Code Online (Sandbox Code Playgroud)