Why is c = 1 in the following code?

Why is c = 1 in the following code?

 #include <stdio.h> int main() { int i = 65537; char c = (char)i; printf("c = %d\n",c); /* why c =1 */ return(0); } 
+6
source share
4 answers

65537 - 0x10001 (in hexadecimal, 10000000000000001 in binary format). If you assign this value a char value whose length is only one byte, you will only accept the low (low) byte from 0x1001, which is 0x01 = 1 in decimal.

+7
source

Char only stores 1 byte. By assigning c to int , only the low byte is assigned.

65537 = 256 * 256 + 1.

Therefore, c = 1.

+5
source

The char type is 8 bits long, and int has 32 bits. When you assign an int variable to a char variable, the value is cut into only the 8 least significant bits.

65537 is in binary format 10000000 000000001

So, the least 00000001 high byte is 00000001

+4
source

This is for casting from int to char: int i = 65537; char c = (char) i;

The first four bytes are set here from 10000000000000001: this is why it comes as 1 if you use 65539 (10000000000000011), char will be 3

0
source

Source: https://habr.com/ru/post/957295/


All Articles