Reputation:
With the following code I declare an unsigned int and assign it the value of 236. I then take the 1's complement of it and assign that to a separate variable. When printed with printf, I expect the 2nd variable to print as "19", but its printing as "4294967059". Why? Doesn't the ~ bitwise operator take the value of the first variable (base 2) and "flip" the bits (1's complement), resulting in "19" in base 10? Ints on my machine are 32-bit, and I assume this has something to do with 2^32-1 (4294967295), but I haven't figured it out
unsigned a = 236; // binary of this 11101100 = 236 base 10
unsigned b = ~a; // 1's complement to 00010011 = 19 base 10
printf("a: %u b: %u",a,b); // prints 236 and 4294967059. WHY?
Upvotes: 2
Views: 335
Reputation: 14505
The binary of a
is 00000000 00000000 00000000 11101100
if unsigned int is 4 bytes long. ~a
is 11111111 11111111 11111111 00010011
, which is 4294967295.
You can use unsigned char to represent a single byte(most likely it's 8 bits).
unsigned char a = 236;
unsigned char b = ~a; // b = 19
Upvotes: 4
Reputation: 47784
"Ints on my machine are 32-bit"
When you say int
on your machine is 32 bit why you just consider 8 bit ?
236 => 00000000000000000000000011101100
1's complement of which is
11111111111111111111111100010011 => 4294967059
Upvotes: 2