0

Help with writing a function to reverse the bits in a byte

/// Reverses the bits in a byte /// @param x - the input byte /// @return - the same byte with the bits reversed uint8_t reverse_bits(uint8_t x)

27th Sep 2021, 7:56 PM
Joseph Ligeikis
Joseph Ligeikis - avatar
5 Answers
+ 3
Martin Taylor , oh right I was just taking 1 as 0b1 rather than 0b00000001 To reverse exactly byte I would only need to add a single counter, something similar to: int k=0; for(;n;n>>=1){ reversed <<= 1; reversed += (n&1); k++; } if(k < 8) reversed <<= 8-k; to add required zeros at the end...
28th Sep 2021, 1:19 AM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
+ 2
Here is a simple way to reverse bits in a number: unsigned int reverse_bits(unsigned int num){ unsigned int reversed = 0; unsigned int n= num; for(;n;n>>=1){ reversed <<= 1; reversed += (n&1); } return reversed; }
27th Sep 2021, 10:44 PM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
+ 1
Thank you for the example! Exatcly what i was looking for.
29th Sep 2021, 2:37 AM
Joseph Ligeikis
Joseph Ligeikis - avatar
0
I understand the reverse of binary code I was trying to write out a code that would reverse the binary code.
27th Sep 2021, 9:35 PM
Joseph Ligeikis
Joseph Ligeikis - avatar
0
I apologize Martin Taylor i am new to this. I am more used to reading rather than writing code. I only have experience with C++ robotic coding.
28th Sep 2021, 3:06 AM
Joseph Ligeikis
Joseph Ligeikis - avatar