在java中将整数转换为字节 [英] Conversion of integer to byte in java

查看:217
本文介绍了在java中将整数转换为字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考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中将整数转换为字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆