在java中将整数转换为字节

编程入门 行业动态 更新时间:2024-10-24 16:27:34
本文介绍了在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中将整数转换为字节

本文发布于:2023-10-24 16:53:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524491.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   转换为   中将   字节   java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!