I have the following code:
#include <stdio.h>
struct test
{
int x: 2;
int y: 2;
};
int main()
{
test t;
t.x = -1;
printf("%d", t.x);
return 0;
}
This snippet prints -1
which I can understand,
If the same code, %d
is replaced with %x
format specifier like below:
#include <stdio.h>
struct test
{
int x: 2;
int y: 2;
};
int main()
{
test t;
t.x = -1;
printf("%x", t.x);
return 0;
}
The output becomes ffffffff
.
Please explain why this is the case.
%x
prints the hex representation of the value of the given argument. The two's complement representation of-1
, in hex, gives you thatffffffff
.FWIW: This outcome is not particularly related to use of bit-filed variable here, as
printf()
is a variadic function.