I came across two different ways to swap nibbles in a byte.
The first version (which I found online https://www.geeksforgeeks.org/dsa/swap-two-nibbles-byte/ ) uses masking:
And then I wrote my own version without any masks on my laptop
I didn’t use any masking here and the output matches what I expect.
Are there any cases where my non-masked version would fail, or both are always equivalent for 8-bit values?
Is masking really necessary ?
The first version (which I found online https://www.geeksforgeeks.org/dsa/swap-two-nibbles-byte/ ) uses masking:
C:
unsigned char swapNibbles(unsigned char x)
{
return ((x & 0x0F) << 4) | ((x & 0xF0) >> 4);
}
C:
#include <stdio.h>
#include <stdint.h>
int main() {
uint8_t byte = 8; // 0000 1000 = 8
byte = (byte << 4) | (byte >> 4); // 1000 0000 = 128
printf("Swap nibble: %u\n", byte);
return 0;
}
Are there any cases where my non-masked version would fail, or both are always equivalent for 8-bit values?
Is masking really necessary ?