2

I'm reading CLR via C# by Jeffrey Richter and on page 115 there is an example of an overflow resulting from arithmetic operations on primitives. Can someone pls explain?

Byte b = 100;
b = (Byte) (b+200); // b now contains 44 (or 2C in Hex).

I understand that there should be an overflow, since byte is an unsigned 8-bit value, but why does its value equal 44?

3 Answers 3

7

100+200 is 300; 300 is (in bits):

1 0010 1100

Of this, only the last 8 is kept, so:

0010 1100

which is: 44

Sign up to request clarification or add additional context in comments.

1 Comment

great explanation using bits :) (+1) from me.
0

The binary representation of 300 is 100101100. That's nine bits, one more than the byte type has room for. Therefore the higher bit is discarded, causing the result to be 00101100. When you translate this value to decimal you get 44.

Comments

0

A byte can hold represent integers in the range between 0 and 255 (inclusive). When you pass a value greater than the 255, like 300, the value of 300-256=44 is stored. This happens because a byte is consisted of 8 bits and each bit can either 0 or 1. So you can represent 2^8=256 integers using a byte, starting from 0.

Actually, you have to divide your number with the 256. The remainder of this can only be represented by a byte.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.