java将一个整数按字节输出,在java中将整数转换为字节

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值