Java如何将int转换为字节? [英] How does Java convert int into byte?
问题描述
int i =132;
byte b =(byte)i;
System.out.println(b);
输出为-124
为什么就是它?我知道这是一个非常基本的问题,但是我仍然无法对其进行映射,或者了解这是如何发生的?
Why is that? I know this is a very basic question, but I'm still not able to map it, or understand how this happens?
推荐答案
在Java中, int
是32位。 字节
是8 位
。
In Java, an int
is 32 bits. A byte
is 8 bits
.
大多数原始类型在Java中签名, byte
, short
, int
, long
以二进制补码编码。 ( 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);
打印出来:签名:-1无符号: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,这是正的),来自字节的原始8位由Java读取为正值。
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屋!