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?
Byte overflow is a problem that needs to be understood when dealing with bytes . If the result is greater than 127 or less than -128, then the byte variable overflows (i.e., it cannot contain the resulting value in a single byte). The remainder result is then displayed instead of the original result.
In computing, an overflow error is an error that happens when a program receives a number, value or variable outside the scope of its ability to handle. This type of error is somewhat common in programming, especially when dealing with integers or other numerical types of variables.
An integer overflow occurs when you attempt to store inside an integer variable a value that is larger than the maximum value the variable can hold. The C standard defines this situation as undefined behavior (meaning that anything might happen).
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)
The top bits will be truncated. It is not harmful to any other memory, it is only harmful in terms of unintended results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With