How to reverse a byte
assembly, atmega, avr, byte, reverse
Solution
Here's a snippet - it's written for the GNU toolchain (avr-gcc, binutils, avr-libc, etc) - but it should be easy to adapt:
static inline __attribute__ ((always_inline))
uint8_t avr_reverse_byte (uint8_t x)
{
x = ((x & 0x55) << 1) | ((x & 0xaa) >> 1);
x = ((x & 0x33) << 2) | ((x & 0xcc) >> 2);
/* x = ((x & 0x0f) << 4) | ((x & 0xf0) >> 4); */
__asm__ ("swap %0" : "=r" (x) : "0" (x)); /* swap nibbles. */
return x;
}
So, not much of an improvement over the 'C' code, except for the final hi-lo nibble swap implemented with the `swap` instruction.
Problem
I am currectly working on a project and it happens that I have to reverse the order of a byte. I am currently using AVR Studio Mega32 Microcontroller. For example: ``` 0000 0001 becomes 1000 0000 0001 0110 becomes 0110 1000 1101 1001 becomes 1001 1011 ``` To start I have this: ``` ldi r20,0b00010110 ``` What is the easiest way to reverse the byte so that r20 becomes 01101000?