Convert int to char C formula

int num = 65537;
char p = (char)num; //char = 1;

      

What's going on here? Is this p=num%(127+128)-1

or p=num%256

or something else? I need to know why p is 1. Thanks!

+3


source to share


2 answers


Short answer: On practically standard processors it is 1, because 65537% 256 == 1. The reason is because one ksmonkey123 is explained.

Note. If you are writing 127 + 128

because the signed char

equivalent bounds char

for typical compilers nowadays are -128 to +127, please remember that the number of values ​​between -128 and +127 is (127 - (-128) + 1), which is also gives 256, so it doesn't matter if you are using bounds signed char

(-128 to 127) or unsigned char

(0 to 255).



Nitpick: In fact, by assigning a value that cannot be represented in the signed target variable, you get undefined behavior, and according to the C standard, all bets are disabled.

Assigning a positive value that does not fit into an unsigned variable results in "mod range" behavior, such as "% 256" for unsigned characters if char is 8 bits. Assigning a negative value to unsigned results in one of the three possible behaviors defined by the standard. An implementation must describe what behavior is used by that implementation. All non-embedded C compilers currently behave like adding a multiple of 2 ^ N, where N is the number of bits of the target type, to the value. So "-510" goes up to +2, adding 2 * 256 to it, and then that +2 is stored in a variable.

+3


source


since 65537 00000000 00000001 00000000 00000001

is binary, but the char type has only 1 byte, the last byte is counted for the char value, which is00000001 = 1



+6


source







All Articles