Java 将 int 转换为 byte 时的奇怪行为? [英] Odd behavior when Java converts int to byte?

查看:28
本文介绍了Java 将 int 转换为 byte 时的奇怪行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int i =132;

byte b =(byte)i; System.out.println(b);

令人难以置信.为什么输出-124?

Mindboggling. Why is the output -124?

推荐答案

在 Java 中,int 是 32 位.一个 byte 是 8 bits .

In Java, an int is 32 bits. A byte is 8 bits .

Java 中的大多数原始类型都是有符号的,byteshortintlong 被编码在二进制补码中.(char 类型是无符号的,符号的概念不适用于boolean.)

Most primitive types in Java are signed, and byte, short, int, and long are encoded in two's complement. (The char type is unsigned, and the concept of a sign is not applicable to boolean.)

在此数字方案中,最高有效位指定数字的符号.如果需要更多位,则将最高有效位(MSB")简单地复制到新的 MSB.

In this number scheme the most significant bit specifies the sign of the number. If more bits are needed, the most significant bit ("MSB") is simply copied to the new MSB.

所以如果你有字节 255:11111111如果您想将其表示为 int(32 位),您只需将 1 向左复制 24 次.

So if you have byte 255: 11111111 and you want to represent it as an int (32 bits) you simply copy the 1 to the left 24 times.

现在,读取负二的补数的一种方法是从最低有效位开始,向左移动直到找到第一个 1,然后反转每一位.结果数字是该数字的正数

Now, one way to read a negative two's complement number is to start with the least significant bit, move left until you find the first 1, then invert every bit afterwards. The resulting number is the positive version of that number

例如:11111111 转到 00000001 = -1.这是 Java 将显示的值.

For example: 11111111 goes to 00000001 = -1. This is what Java will display as the value.

您可能想做的是知道字节的无符号值.

What you probably want to do is know the unsigned value of the byte.

您可以使用位掩码来完成此操作,该位掩码会删除除最低有效 8 位之外的所有内容.(0xff)

You can accomplish this with a bitmask that deletes everything but the least significant 8 bits. (0xff)

所以:

byte signedByte = -1;
int unsignedByte = signedByte & (0xff);

System.out.println("Signed: " + signedByte + " Unsigned: " + unsignedByte);

将打印出:"Signed: -1 Unsigned: 255"

这里到底发生了什么?

我们使用按位与来屏蔽所有无关的符号位(最低有效 8 位左侧的 1.)当一个 int 转换为一个字节时,Java 会砍掉最左边的 24 位

We are using bitwise AND to mask all of the extraneous sign bits (the 1's to the left of the least significant 8 bits.) When an int is converted into a byte, Java chops-off the left-most 24 bits

1111111111111111111111111010101
&
0000000000000000000000001111111
=
0000000000000000000000001010101

由于第 32 位现在是符号位而不是第 8 位(并且我们将符号位设置为 0,这是正数),因此 Java 将字节中的原始 8 位读取为正值.

Since the 32nd bit is now the sign bit instead of the 8th bit (and we set the sign bit to 0 which is positive), the original 8 bits from the byte are read by Java as a positive value.

这篇关于Java 将 int 转换为 byte 时的奇怪行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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