0

let i have got two byte variable:

byte a= 255;
byte b= 121;

byte c= (byte) (a + b);

Console.WriteLine(c.ToString());

output:120

please explain me how this is adding values. i know that its crossing size limit of byte but don't know what exactly operation it performs in such situation because its not looking like its chopping the result.

Thanks

EDIT: sorry its 120 as a answer.

Dirk Vollmar
  • 172,527
  • 53
  • 255
  • 316
Dr. Rajesh Rolen
  • 14,029
  • 41
  • 106
  • 178
  • 2
    That is unusual. I would have expected `120` as the output. – Gabe Nov 16 '10 at 13:13
  • Your sample does not compile. Did you mean `byte c = (byte) (a + b)`? – Dirk Vollmar Nov 16 '10 at 13:14
  • possible duplicate of [What actually happens when a Byte overflows?](http://stackoverflow.com/questions/4156967/what-actually-happens-when-a-byte-overflows) – H H Nov 16 '10 at 13:54

4 Answers4

8

You are overflowing the byte storage of 255 so it starts from 0.

So: a + b is an integer = 376

Your code is equivalent to:

byte c = (byte)376;

That's one of the reasons why adding two bytes returns an integer. Casting it back to a byte should be done at your own risk.

If you want to store the integer 376 into bytes you need an array:

byte[] buffer = BitConverter.GetBytes(376);

As you can see the resulting array contains 4 bytes now which is what is necessary to store a 32 bit integer.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
5

It gets obvious when you look at the binary representation of the values:

var | decimal | binary
----|----------------------
  a |     255 |   1111 1111
  b |     121 |   0111 1001
    |         |
a+b |     376 | 1 0111 1000

This gets truncated to 8 bits, the overflow bit is disregarded when casting the result to byte:

  c |         |   0111 1000 => 120
Dirk Vollmar
  • 172,527
  • 53
  • 255
  • 316
1

As others are saying, you are overflowing; the a+b operation results in an int, which you are explicitly casting to a byte. Documentation is here, essentially in an unchecked context, the cast is done by truncating the most significant bits.

Chris Shaffer
  • 32,199
  • 5
  • 49
  • 61
0

I guess you mean byte c= (byte)(a + b);

On my end the result here is 120, and that is what I would expect.

a+b equals 376, and all bits that represent 256 and up gets stripped (since byte actually only hold 1 byte), then 120 is what you are left with inside your byte.

Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151