Java中从int到byte的显式转换 [英] Explicit conversion from int to byte in Java

查看:105
本文介绍了Java中从int到byte的显式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将int转换为byte。

I am trying to convert an int to byte.

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

我知道-128到127的字节范围以及将整数存储到一个字节的规则是:

I know the range of byte if -128 to 127 and the rule of storing an integer to a byte is :

byte_value = int_vale%byte_Range; (我发现在完整参考Java中)

byte_value = int_vale % byte_Range; (I found that in Complete reference Java)

当我将它应用于int 128时,它应该是这样的:

When I apply this to int 128 it should be like this:

byte_value = 128%256 = 128;

byte_value = 128%256 = 128;

但实际上是:-128

But, it actually is : -128

我是无法理解这背后的实际逻辑。
请帮助!!

I am not able to understand the actual logic behind this. Please help!!

推荐答案

逻辑很简单,Java编号总是用二进制补码。

Logic is simple, Java numbers are always signed in two's complement.

现在一个字节有8位,128是 10000000 。当你这样做时

Now a byte has 8 bits and 128 is 10000000. When you do

int i = 128

你最终得到:

i == 00000000 00000000 00000000 10000000

当你将它强制转换为一个字节时,你最有意义的24个被截断,所以你最终得到了

When you cast it to a byte you the 24 most significative are truncated, so you end up with

b == 10000000

但Java 字节已签名,128无法表示,因为它溢出并包裹。那么接下来的结果是该值最终为 128 - 256 = -128 (这是因为两个补码)。

but a Java byte is signed, and 128 can't be represented, since it overflows and wraps around. So what happens is that the value ends up as 128 - 256 = -128 (that's because of two's complement).

这篇关于Java中从int到byte的显式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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