1

Referring to page number 79 of " Java The complete Reference" 7th edition by Herbert Schildt. The author says : " If the integer’s value is larger than the range of a byte, it will be reduced modulo (the remainder of an integer division by the) byte’s range".

The range of byte in java is -128 to 127. So the maximum value that fits in a byte is 128. If an integer value is assigned to a byte as shown below :

int i = 257; byte b; b = (byte) i; 

Since 257 crosses the range 127, 257 % 127 = 3 should be stored in 'b'. But am getting the output as 1 instead of 3. Where have I gone wrong in understanding the concept?

1
  • I think the author you quote got it wrong. What does he mean by the "byte's range?" Whether you take that to mean 127 (as you did) or 128 or 256, it doesn't work. (eg 129%128=1 whereas (byte)129 = -127) Commented Jul 28, 2015 at 11:40

2 Answers 2

7

Just consider the binary representation of the numbers :

257 is represented in binary as 00000000 00000000 00000001 00000001 

When you cast this 32 bits int to an 8 bits byte, you keep only the lowest 8 bits :

00000001 

which is 1

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

1 Comment

And it's worth mentioning that if bit 7 is set (the top bit in the byte) then the result will be negative.
2

257 = 00000000 000000000 00000001 00000001 in bits and a byte is made up of 8 bits only...

As a result only the lower 8 bits are stored and 1 is the output.

3 Comments

The value of last 8 bits is 1, that's ok. Does it mean that there won't be any modulo operation?
No there won't be a modulo operation... Its not needed... there is just casting...
Modulo is division. Casting to a smaller size causes truncation, which is different to division. There is no equivalent modulo operation that can have the same effect on 2's compliment signed numbers. The book is wrong.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.