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?
解决方案
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
Java byte类型溢出解析
本文探讨了Java中byte类型的整数溢出行为,并通过具体示例解释了当整数赋值超过byte范围时,如何通过取模运算来确定实际存储的值。文章澄清了一个常见误解,即257赋值给byte类型变量后的结果为何为1而非3。
476

被折叠的 条评论
为什么被折叠?



