Reputation: 10204
I do not see why 3 & 0x1111 = 1 ? It seems that:
for any unsigned 32-bit integer i, i & 0x1111 should be i, right?
However when I tried this on ubuntu 14.04, I got 3 & 0x1111=1
. Why?
int main() {
unsigned int a =3;
printf("size of a= %lu\n",sizeof(a));
printf("value of 3 & 0x1111= %d\n",a & 0x1111);
return 0;
}
Upvotes: 3
Views: 871
Reputation: 2851
The & operator applies the binary and. The 0x means hexadecimal not binary so if we write 0x1111 into a binary we will get: 0001 0001 0001 0001 binary. 3 binary is 011
and
0001 0001 0001 0001 &
0000 0000 0000 0011 =
0000 0000 0000 0001 = 1
Upvotes: 1
Reputation: 13356
In C, any numeric literal starting with 0x
is a hexadecimal number. So the bitmask you are using is 1111
in hexadecimal. In the mask, bits #0, #4, #8 and #12 are 1
s, and the rest are 0
s. That's why you're getting 1
.
0x1111 = 0000 0000 0000 0000 0001 0001 0001 0001 in binary
3 = 0000 0000 0000 0000 0000 0000 0000 0011 in binary
------------------------------------------------
1 = 0000 0000 0000 0000 0000 0000 0000 0001 after doing biwise AND
If you want to construct a mask with all 1
s, in hex, it should be
0xffffffff = 1111 1111 1111 1111 1111 1111 1111 1111
Upvotes: 7
Reputation: 38130
0x1111 is 4369, or as binary: 0001000100010001 So, 3 (0011) masked against that is going to be 0001. Similarly, 19 (0001011) would be 17 (00010001)
Upvotes: 2
Reputation: 224362
3d = 3h = 11b
1111h = 0001000100010001b
so:
0001000100010001b
& 11b
-------------------
1b
Upvotes: 4
Reputation: 18371
0x1111
is 0001000100010001
in binary. So 0x1111 & 3
is 0001000100010001 & 0000000000000011 = 0000000000000001
Upvotes: 3
Reputation: 93181
Convert both of them to binary:
0x1111 = 0001 0001 0001 0001
3 = 0000 0000 0000 0011
When you &
them bit by bit, what else do you expect?
Upvotes: 17