Reputation:
Why in the next code c = 1
?
#include <stdio.h>
int main()
{
int i = 65537;
char c = (char)i;
printf("c = %d\n",c); /* why c =1 */
return(0);
}
Upvotes: 6
Views: 351
Reputation: 25874
65537 is 0x10001 (in hexadecimal, 10000000000000001 in binary). If you cast this value to char
, which is only one byte long, you will only be taking the lowest (least-significant) byte from 0x1001, which is 0x01 = 1 in decimal.
Upvotes: 7
Reputation: 372
This for casting from int to char: int i = 65537; char c = (char)i;
First four bytes are casted here from 10000000000000001: this is why it coming as 1 if you use 65539 (10000000000000011), char will be 3
Upvotes: 0
Reputation: 141
The char type is only 8 bits long, while int has 32 bits. When you assign an int variable to a char, the value is cut to just the 8 least significant bits.
65537 is in binary 10000000 000000001
So, the least significant byte is 00000001
Upvotes: 4
Reputation: 107337
Char stores only 1 byte. By assigning c
to an int
value, only the lowest byte is assigned.
65537 = 256 * 256 + 1.
Hence c = 1.
Upvotes: 4