Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What actually happens when a Byte overflows?

Tags:

c#

byte

carryflag

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?

like image 285
ImJames Avatar asked Nov 11 '10 16:11

ImJames


People also ask

What happens when a byte overflows?

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.

What happens in an overflow error?

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.

What happens when integer overflow in C?

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).


2 Answers

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)

like image 146
Sam Avatar answered Sep 30 '22 03:09

Sam


The top bits will be truncated. It is not harmful to any other memory, it is only harmful in terms of unintended results.

like image 27
Gavin H Avatar answered Sep 30 '22 03:09

Gavin H