For example, in PHP, how would I reverse the bits of the byte 11011111
to 11111011
?
You may use a table that store the reverse value of each byte with (i * 0x0202020202ULL & 0x010884422010ULL) % 0x3ff, initialized through a lambda (you will need to compile it with g++ -std=c++1z since it only works since C++17), and then return the value in the table will give you the accordingly reversed bit:
As for the leap that reversing an 8 bit integer is the same as reversing 4 bit parts then swapping them; I claim experience and intuition (or magic). If you are talking about a single byte, a table-lookup is probably the best bet, unless for some reason you don't have 256 bytes available.
Probably the most logical, consists in rotating the byte while applying a mask on the first bit (n & 1): unsigned char reverse_bits (unsigned char b) { unsigned char r = 0; unsigned byte_len = 8; while (byte_len--) { r = (r << 1) | (b & 1); b >>= 1; } return r; }
In IBM 360 Assembler, assuming the byte you wish to reverse the bits of is at a memory location called “BYTE” and the result replaces the original (…’s to show spacing only). Only 4 instructions and no loop. It really depends how many bits you are wanting to reverse.
If you have already the bits in the form of a string, use strrev.
If not, convert first the byte to its binary representation by using decbin, then reverse using strrev, then go back to byte (if necessary) by using bindec.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With