Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse bits of a byte?

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

like image 352
secret Avatar asked Nov 06 '09 16:11

secret


People also ask

How to get the reverse of a byte in C++?

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:

How do you reverse an 8 bit integer?

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.

What is the most logical way to rotate a byte?

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

How do I reverse a byte in IBM 360 assembly?

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.


1 Answers

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.

like image 152
Konamiman Avatar answered Oct 05 '22 12:10

Konamiman