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 asxisunsigned char). - HolyBlackCat((x<<4) | (x>>4))will actually not give the correct result, sincexis promoted to int before doing the shift. Only by converting to unsigned char in thereturndo we get the correct result. - Falk Hüffnerunsigned charis always zero-extended to int, not signed-extended, hence there's no 1 in the high bytes - phuclv