参考Herbert Schildt的第7版Java The Complete Reference第79页。 作者说:如果整数的值大于字节的范围,它将以模数(整数除法的余数除以)字节的范围。
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".
java中的字节范围是-128到127.因此,适合一个字节的最大值是128.如果将一个整数值赋给一个字节,如下所示:
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;由于257越过127的范围,257%127 = 3应该存储在'b'中。 但我得到的输出是1而不是3. 我在理解这个概念时哪里出错了?
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将此32位 int 转换为8位 byte ,您只保留最低的8位:
When you cast this 32 bits int to an 8 bits byte, you keep only the lowest 8 bits :
00000001这是1
更多推荐
在java中将整数转换为字节
发布评论