0
Why this code shows output as "-121"
Character output https://code.sololearn.com/cuR8WBXKw0VV/?ref=app
2 Answers
+ 3
The char type is only 8 bits. It can represent 2^8 = 256 distinct values. As a signed type it has a range of -128 to +127. The highest bit is used as the sign bit (0 = positive, 1 = negative), and the remaining 7 bits represent the value.
When you add 10 to 125 it reaches the highest positive value (127), sets the sign bit, and wraps around 8 more into the lowest negative values. It counts this way: 126, 127, -128, -127, -126, -125, -124, -123, -122, -121.
If you want to better understand negative numbers in binary, then look up "two's complement" representation.
+ 2
The ASCII table has 127 entries. When you put char c = 125 you are attributing c with the caracter on the 125° ASCII entry.
Now, but why -121? If you know a little of binary, when you 127 = 2^7-1, so I need 7 bits to represent the number, if you add 1 to 127 you will get overflowed because you need 8 bits to represent 128.
But still, why -121? To represent negative numbers we need to add an initial bit that represents the signal 0 for positives and 1 for negatives, guess what? 128 is 10000000, to get the real value we need to use the complement of 2 and it will give us -128.
Ok, now the math: 125+10 = (127+1) + 7 = -128 + 7 = -121
I hope I helped and Keep the good coding :)