What actually happens when a Byte overflows?
Solution 1
It's quite simple. It just does the addition and comes off at a number with more than 8 bits. The ninth bit (being one) just 'falls off' and you are left with the remaining 8 bits which form the number 94.
(yes it's harmless)
Solution 2
The top bits will be truncated. It is not harmful to any other memory, it is only harmful in terms of unintended results.
Solution 3
In C# if you have
checked { byte byte3 = byte1 + byte2; }
It will throw an overflow exception. Code is compiled unchecked
by default. As the other answers are saying, the value will 'wrap around'. ie, byte3 = (byte1 + byte2) & 0xFF;
Solution 4
Typically (and the exact behaviour will depend on the language and platform), the result will be taken modulo-256. i.e. 150+199 = 349. 349 mod 256 = 93.
This shouldn't affect any other storage.
Solution 5
The carry flag gets set... but besides the result not being what you expect, there should be no ill effects.
ImJames
Updated on June 15, 2022Comments
-
ImJames about 2 years
What actually happens when a Byte overflows?
Say we have
byte byte1 = 150; // 10010110 byte byte2 = 199; // 11000111
If we now do this addition
byte byte3 = byte1 + byte2;
I think we'll end up with byte3 = 94 but what actually happens? Did I overwrite some other memory somehow or is this totally harmless?