简体   繁体   English

Java中整数到字节的转换

[英]Conversion of integer to byte in java

Referring to page number 79 of " Java The complete Reference" 7th edition by Herbert Schildt. 参见Herbert Schildt撰写的“ Java完整参考”第七版的第79页。 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 : java中字节的范围是-128到127。因此,适合字节的最大值是128。如果将整数值分配给字节,如下所示:

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

Since 257 crosses the range 127, 257 % 127 = 3 should be stored in 'b'. 由于257跨越范围127,因此应将257%127 = 3存储在'b'中。 But am getting the output as 1 instead of 3. Where have I gone wrong in understanding the concept? 但是我得到的输出是1而不是3。我在理解这个概念时哪里出错了?

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 : 当将此32位int转换为8位byte ,仅保留最低的8位:

00000001

which is 1 这是1

257 = 00000000 000000000 00000001 00000001 in bits and a byte is made up of 8 bits only... 257 = 00000000 000000000 00000001 00000001以位为单位,一个字节仅由8位组成...

As a result only the lower 8 bits are stored and 1 is the output. 结果,仅低8位被存储,输出为1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM