+ 1

How to reverse the 8-bits in byte by c Code?

I think it may be like circular shift left, but didn't work with me

16th Oct 2018, 3:35 PM
Aisha Ali
Aisha Ali - avatar
4 Answers
+ 3
You forgot to store your shift of num back into it. Try this: num >>=1;
17th Oct 2018, 3:57 PM
John Wells
John Wells - avatar
+ 1
for(int i=8; i; i=i-1) {result = (result << 1) + (source & 1); source>>=1}
16th Oct 2018, 3:52 PM
Sergey Ushakov
Sergey Ushakov - avatar
+ 1
right. Fixed.
17th Oct 2018, 5:44 PM
Sergey Ushakov
Sergey Ushakov - avatar
0
I tried this, but it gives me reversed num= 255 not 128!, how to fix? #include <stdio.h> #include <stdlib.h> void Reverse_8_bits(unsigned char num) { unsigned char i; unsigned char result; for(i=8; i>0 ; i--) { result = ((result << 1) + (num & 1)); num >>1; } printf("Reversed num= %hhu", result); } int main() { Reverse_8_bits(1); return 0; }
17th Oct 2018, 9:54 AM
Aisha Ali
Aisha Ali - avatar