I’ve been writing a program in C to move the first 4 bits of a char to the end and the last 4 to the start. For most values it works normally, as well as the reverse operation, but for some values, as 8, x, y, z, it gives as result a 32 bit value. Values checked through printing hex value of the variable. Can anybody explain why this is happening?
#include <stdio.h>
#include <stdlib.h>
int main()
{
char o, f,a=15;
scanf("%c",&o);
printf("o= %d\n",o);
f=o&a;
o=o>>4;
printf("o= %d",o);
o=o|(f<<4);
printf("o= %x, size=%d\n",o,sizeof(o));
f=o&a;
o=o>>4;
printf("o= %d",o);
o=o|(f<<4);
printf("o= %x, size=%d\n",o,sizeof(o));
return 0;
}
Passing
oas an argument toprintf()results in an automatic conversion toint, which is apparently 32-bit on your system. The automatic conversion uses sign-extension, so if bit 7 inois set, bits 8-31 in the converted result will be set, which will explain what you are seeing.You could use
unsigned charinstead ofcharto avoid this. Or passo & 0xfftoprintf().