+ 1
Assign char var greater than 127 into int var turns into negative number
https://code.sololearn.com/c5DB4pm1FMJr/?ref=app I run this code and get that the 32 bits of the integer variable turn to 1 (24 msbs) so i get a different number. Why? I know i should use atoi but still I don't understand what exactly happens...
2 odpowiedzi
+ 9
char variables are 1 byte, and are signed by default on this compiler and system, so they range from -128 to +127.
Converting from int to char. truncates/ignores everything except the rightmost byte. And assigning a value higher than +127 to a char wraps it around into negatives.
The leftmost bit (the sign bit) in a signed value is 0 when positive and 1 when negative. So assigning a higher number carries a 1 into the sign bit, which is why it wraps around.
If you want a little more range to a char, declare it as an unsigned char, which ranges 0 to 255. You'll get the same characters. Ex: 129 (unsigned) = -127 (signed) = ü (char)
+ 1
Oh thanks, my mistake was the assumption that char's range is between 0 to 255 like the ascii table's range