Why this code shows output as "-121" | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
0

Why this code shows output as "-121"

Character output https://code.sololearn.com/cuR8WBXKw0VV/?ref=app

17th Oct 2022, 7:16 AM
Yogeshwaran P
Yogeshwaran P - avatar
2 Réponses
+ 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.
17th Oct 2022, 11:44 AM
Brian
Brian - avatar
+ 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 :)
17th Oct 2022, 11:50 AM
Tomás Ribeiro
Tomás Ribeiro - avatar