Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reverse the ON bits in a byte?

I was reading Joel's book where he was suggesting as interview question:

Write a program to reverse the "ON" bits in a given byte.

I only can think of a solution using C.

Asking here so you can show me how to do in a Non C way (if possible)

like image 677
prakash Avatar asked Aug 13 '08 13:08

prakash


People also ask

How do you reverse a bit?

Repeating the same permutation twice returns to the original ordering on the items, so the bit reversal permutation is an involution. This permutation can be applied to any sequence in linear time while performing only simple index calculations.

Which operator is used to reverse the bits?

Bitwise complement operator is used to reverse the bits of an expression.

How do you invert a binary number?

In binary, when we subtract a number A from a number of all 1 bits, what we're doing is inverting the bits of A. So the subtract operation is the equivalent of inverting the bits of the number. Then, we add one.


3 Answers

I claim trick question. :) Reversing all bits means a flip-flop, but only the bits that are on clearly means:

return 0;
like image 153
GManNickG Avatar answered Oct 22 '22 13:10

GManNickG


What specifically does that question mean?

Good question. If reversing the "ON" bits means reversing only the bits that are "ON", then you will always get 0, no matter what the input is. If it means reversing all the bits, i.e. changing all 1s to 0s and all 0s to 1s, which is how I initially read it, then that's just a bitwise NOT, or complement. C-based languages have a complement operator, ~, that does this. For example:

unsigned char b = 102;      /* 0x66, 01100110 */
unsigned char reverse = ~b; /* 0x99, 10011001 */
like image 41
Jason Day Avatar answered Oct 22 '22 11:10

Jason Day


What specifically does that question mean?

Does reverse mean setting 1's to 0's and vice versa?

Or does it mean 00001100 --> 00110000 where you reverse their order in the byte? Or perhaps just reversing the part that is from the first 1 to the last 1? ie. 00110101 --> 00101011?

Assuming it means reversing the bit order in the whole byte, here's an x86 assembler version:

; al is input register
; bl is output register

xor bl, bl      ; clear output

; first bit
rcl al, 1       ; rotate al through carry
rcr bl, 1       ; rotate carry into bl

; duplicate above 2-line statements 7 more times for the other bits

not the most optimal solution, a table lookup is faster.

like image 4
Lasse V. Karlsen Avatar answered Oct 22 '22 12:10

Lasse V. Karlsen