Byte = 8 bits, Nibble = 4 bits
Some times you need to flip a byte or nibble from LSB to MSB.
For example "1100 0101" to "1010 0011"
Took me a while to find this, so I thought I'd share. Any comments or improvements welcome. (I'm not an expert coder, so I'm sure one of you wizards can polish this quite a bit.)
// send nibbleShift a decimal number
// example "nibbleShift(3)" returns '12'
// "0011" becomes "1100"
int nibbleShift(int num) {
int var = 0;
int i, x, y, p;
int s = 4; // number of bits in 'num'. (This case a 4bit nibble)
for (i = 0; i < (s / 2); i++) {
// extract bit on the left, from MSB
p = s - i - 1;
x = num & (1 << p);
x = x >> p;
// extract bit on the right, from LSB
y = num & (1 << i);
y = y >> i;
var = var | (x << i); // apply x
var = var | (y << p); // apply y
}
return var;
}
To flip a whole byte, change the size of 's' to 8
Then if you input '3' you'll get '192' as the result.
"0000 0011" becomes "1100 000"
The other route with a nibble or byte flip is to do a table lookup. I'd be curious to hear what you think about which would be faster an the arduino; doing a table lookup or manually calculating it ??