How to reverse a byte?

I'm trying to create an animation on an LCD display using custom characters. I don't want to define every single custom character. Some characters are reusable if you simply flip them.

A 8x5 custom character is defined like this:
byte blankChar[8] = {B00000,B00000,B00000,B00000,B00000,B00000,B00000,B00000};

To flip that character on the horizontal axis you just need to change the order of the bytes. But to flip it on the vertical axis you would need to reverse the bytes.

What I mean is B00111 should be turned into B11100, or B10000 to B00001. How do I do that?

http://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious

Manually with bitwise operators. I don't think there's a more graceful way.

end = ((start&0x01)<<7)|((start&0x02)<<5)|((start&0x04)<<3)|((start&0x08)<<1)|((start&0x10)>>1)|((start&0x20)>>3)|((start&0x40)>>5)|((start&0x80)>>7);

or loop through it like

byte end=0;
for (byte x=0;i<8;i++) {
end = end <<1; //push bits already in there over by one
end |= ((start>>i) & 0x01); //shift start x bits to the right, bitwise and with 1. |= is bitwise-or-equals, same idea as += and the like. 
}

Code not tested, no warranty against typos.

Bitwise NOT or play with assembly XOR few ways of doing it

As there are only 256 bytes a look-up table in the form of an array of the reversed values might be the quickest. For example

reversedValue = lookupTable[forwardValue];

...R

// reverse the bit order of bits
__builtin_avr_insert_bits (0x01234567, bits, 0)

westfw:

// reverse the bit order of bits

__builtin_avr_insert_bits (0x01234567, bits, 0)

Usage explained: AVR Built-in Functions (Using the GNU Compiler Collection (GCC))

Multiple approaches presented at https://www.avrfreaks.net/forum/optimal-byte-flipping

You guys missed that reversal of 5 bits is needed, not 8.

Try again. :wink:

Jatoxo:
A 8x5 custom character

What I mean is B00111 should be turned into B11100, or B10000 to B00001.

that's only 32... not bad for a look up

oqibidipo:
You guys missed that reversal of 5 bits is needed, not 8.

Try again. :wink:

Insert bits is easily modified to : __builtin_avr_insert_bits (0xFFF01234, bits, 0)