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

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

问题描述

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"

这里实际上发生了什么?

What's actually happening here?

我们正在使用按位与(AND)屏蔽所有无关符号位(最低有效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转换为字节时的奇怪行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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