int num = 65537;
char p = (char)num; //char = 1;
Whats going on here?
Is it p=num%(127+128)-1
or p=num%256 or something else?
I need to know why p is equal to 1.
thanks!
int num = 65537;
char p = (char)num; //char = 1;
Whats going on here?
Is it p=num%(127+128)-1
or p=num%256 or something else?
I need to know why p is equal to 1.
thanks!
Copyright © 2021 Jogjafile Inc.
Short answer: In practice on standard processors, it is 1 because 65537 % 256 == 1. The reason is the one ksmonkey123 explained.
Note: If you were writing
127 + 128because the bounds of asigned char, which is equivalent tocharon typical compilers nowadays, are -128 to +127, please remember that the number of values between -128 and +127 is (127 - (-128) + 1), which also yields 256, so it does not matter whether you use the bounds ofsigned char(-128 to 127) orunsigned char(0 to 255).Nitpick: Actually, assigning a value that can not be represented in an signed destination variable, you get undefined behaviour, and according to the C standard, all bets are off.
Assigning a positive value that does not fit into an unsigned variable yields "mod range" behaviour, like "%256" for unsigned chars if char has 8 bits. Assigning a negative value into an unsigned variable results in one of three possible behaviours defined by the standard. The implementation has to describe which behaviour is used by that implementation. All non-embedded C compilers nowadays behave like adding a multiple of 2^N, where N is the number of bits of the target type, to the value. So "-510" gets to +2 by adding 2*256 to it, and then this +2 is stored in the variable.