5+30 is 135. However, this is above the maximum value of byte. So Java wraps around to the minimum value of byte rather than stopping at the maximum value.
Note you were using 131 as the second term in that addition, and the original post said 130. The results follow the usual rules about arithmetic overflow errors in two's complement arithmetic.
Campbell Ritchie
Marshal
Posts: 64102
215
posted 7 months ago
What happens for such overflow is this:-The bit₂₄ of the int becomes the bit₀ of the byte and (this isn't an accurate description of complementary arithmetic) becomes equivalent to −128 in decimal. A bit₀ in a two's complement number is always negative.
Dimitrios Tosidis
Greenhorn
Posts: 2
posted 7 months ago
You are absolutely right.
I was referring to the Number Circle for Two's Complement numbers.
When you are adding 1 to the maximum value then you go to the minimum value and the opposite.
135 is outside the range of a byte which is -128 to 127. Instead the top bit of the 8-bit value is treated as the signed which indicates it is negative in this case. So the number is 135 - 256 = -121.
Campbell Ritchie
Marshal
Posts: 64102
215
posted 6 months ago
Welcome to the Ranch
The bit₇ in an 8‑bit two's complement number isn't a true sign bit. Otherwise you would have 1010_1010 = −42 and 0010_1010 = 42. The bit₇ has a value of −128, so 1010_1010 = −86, 0010_1010 = 42, and 1000_0000 = −128.
A day job? In an office? My worst nightmare! Comfort me tiny ad!
Create Edit Print & Convert PDF Using Free API with Java