How to reverse bits of a byte?

前端 未结 8 2350
广开言路
广开言路 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:27

    The straight forward approach is to perform 8 masks, 8 rotates, and 7 additions:

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

提交回复
热议问题