[SOLVED] How to reverse the bits in a byte?

Status
Not open for further replies.

agg_mayur

Member level 3
Joined
Feb 25, 2010
Messages
66
Helped
3
Reputation
6
Reaction score
3
Trophy points
1,288
Location
India
Activity points
1,715
How to reverse the bits in a byte, for e.g. i have
LSB----------MSB
0 1 1 0 0 1 1 1
should be convert to
MSB----------LSB
1 1 1 0 0 1 1 0
and vice versa?
 

Because no microcontroller has a built in hardware instruction for bit reversal, you usually do it in a loop, utilizing shift instructions. I guess, you can easily figure out the C code for the operation.

The fastest method is however a ROM table of 256 bytes, that holds the reversed code for each possible input byte.
 

hi,

try to test this code in C!

byte input
byte output
byte bit

output_byte=0

for(count=1;count<=8;count++)
{ bit= input & 0x01;
input=input>>1;
output=output<<1;
if(bit==1)
output=output+1;

}
 
@pmar_kpj
Thankyou for the solution it works!!

---------- Post added at 11:01 ---------- Previous post was at 11:00 ----------

One more solution i got from somewhere which i want to share:
for(count=1;count<=8;count++)
{
bit = num & 0x01;
num = num>>1;
output = output<<1;
if(bit==1)
output = output+1;
}
 

Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…