How to reverse bits of a byte?

前端 未结 8 2355
广开言路
广开言路 2021-02-09 13:09

For example, in PHP, how would I reverse the bits of the byte 11011111 to 11111011?

8条回答
  •  再見小時候
    2021-02-09 13:36

    Check the section on reversing bit sequences in Bit Twiddling Hacks. Should be easy to adapt one of the techniques into PHP.

    While probably not practical for PHP, there's a particularly fascinating one using 3 64bit operations:

    unsigned char b; // reverse this (8-bit) byte
    b = (b * 0x0202020202ULL & 0x010884422010ULL) % 1023;
    

提交回复
热议问题