Consider the code below which swaps nibbles in a byte:
#include <stdio.h>
unsigned char swapNibbles(unsigned char x)
{
return ( (x & 0x0F)<<4 | (x & 0xF0)>>4 );
}
int main()
{
unsigned char x = 100;
printf("%u", swapNibbles(x));
return 0;
}
Why is anding with 0x0F and 0xF0 necessary? Instead I can just write
return ((x<<4) | (x>>4));
I have googled about it and people seem to say that it won't work with negative numbers as it would pad the number with ones in right shift however anding with 0xF0 would not make the number positive? What am I missing?
((x<<4) | (x>>4))
will work (as long asx
isunsigned char
). – HolyBlackCat Nov 4 '17 at 19:36((x<<4) | (x>>4))
will actually not give the correct result, sincex
is promoted to int before doing the shift. Only by converting to unsigned char in thereturn
do we get the correct result. – Falk Hüffner Nov 5 '17 at 9:46unsigned char
is always zero-extended to int, not signed-extended, hence there's no 1 in the high bytes – phuclv Nov 5 '17 at 10:36