Java 中如何将整数转换为字节?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2458495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:59:50  来源:igfitidea点击:

How are integers cast to bytes in Java?

javaintbytecasting

提问by LandonSchropp

I know Java doesn't allow unsigned types, so I was wondering how it casts an integer to a byte. Say I have an integer a with a value of 255 and I cast the integer to a byte. Is the value represented in the byte 11111111? In other words, is the value treated more as a signed 8 bit integer, or does it just directly copy the last 8 bits of the integer?

我知道 Java 不允许无符号类型,所以我想知道它如何将整数转换为字节。假设我有一个值为 255 的整数 a 并且我将整数转换为一个字节。该值是否以字节 11111111 表示?换句话说,该值是否更多地被视为有符号的 8 位整数,还是只是直接复制整数的最后 8 位?

采纳答案by Michael Myers

This is called a narrowing primitive conversion. According to the spec:

这称为缩小原语转换。根据规范:

A narrowing conversion of a signed integer to an integral type Tsimply discards all but the nlowest order bits, where nis the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.

有符号整数到整数类型T的缩窄转换只会丢弃除n 个最低位之外的所有位,其中n是用于表示类型T的位数。除了可能丢失有关数值大小的信息之外,这还可能导致结果值的符号与输入值的符号不同。

So it's the second option you listed (directly copying the last 8 bits).

所以这是您列出的第二个选项(直接复制最后 8 位)。

I am unsure from your question whether or not you are aware of how signed integral values are represented, so just to be safe I'll point out that the byte value 1111 1111 is equal to -1 in the two's complementsystem (which Java uses).

我不确定你的问题是否知道有符号整数值是如何表示的,所以为了安全起见,我会指出字节值 1111 1111 在二进制补码系统中等于 -1 (Java 使用)。

回答by Buhake Sindi

Just a thought on what is said: Always mask your integer when converting to bytes with 0xFF(for ints). (Assuming myInt was assigned values from 0 to 255).

只是想一想所说的话:在转换为带有0xFF(对于整数)的字节时,始终屏蔽您的整数。(假设 myInt 被分配了从 0 到 255 的值)。

e.g.

例如

char myByte = (char)(myInt & 0xFF);

why? if myInt is bigger than 255, just typecasting to byte returns a negative value (2's complement) which you don't want.

为什么?如果 myInt 大于 255,只需将类型转换为 byte 即可返回您不想要的负值(2 的补码)。

回答by Roman

or does it just directly copy the last 8 bits of the integer

还是直接复制整数的最后 8 位

yes, this is the way this casting works

是的,这就是这个演员的工作方式

回答by Paul

int i = 255;

byte b = (byte)i;

So the value of be in hex is 0xFF but the decimal value will be -1.

所以十六进制的值为 0xFF 但十进制值为 -1。

int i = 0xff00;

byte b = (byte)i;

The value of b now is 0x00. This shows that java takes the last byte of the integer. ie. the last 8 bits but this is signed.

b 现在的值是 0x00。这表明 java 取整数的最后一个字节。IE。最后 8 位,但这是有符号的。

回答by Art Swri

for (int i=0; i <= 255; i++) {
    byte b = (byte) i;    // cast int values 0 to 255 to corresponding byte values 
    int neg = b;     // neg will take on values 0..127, -128, -127, ..., -1
    int pos = (int) (b & 0xFF);  // pos will take on values 0..255
}

The conversion of a byte that contains a value bigger than 127 (i.e,. values 0x80 through 0xFF) to an int results in sign extension of the high-order bit of the byte value (i.e., bit 0x80). To remove the 'extra' one bits, use x & 0xFF; this forces bits higher than 0x80 (i.e., bits 0x100, 0x200, 0x400, ...) to zero but leaves the lower 8 bits as is.

将包含大于 127 的值(即值 0x80 到 0xFF)的字节转换为 int 会导致字节值的高阶位(即位 0x80)的符号扩展。要删除“额外”一位,请使用 x & 0xFF; 这会强制高于 0x80 的位(即位 0x100、0x200、0x400,...)为零,但保留低 8 位不变。

You can also write these; they are all equivalent: int pos = ((int) b) & 0xFF; // convert b to int first, then strip high bits int pos = b & 0xFF; // done as int arithmetic -- the cast is not needed

你也可以写这些;它们都是等价的: int pos = ((int) b) & 0xFF; // 先将 b 转换为 int,然后去掉高位 int pos = b & 0xFF; // 作为 int 算术完成——不需要强制转换

Java automatically 'promotes' integer types whose size (in # of bits) is smaller than int to an int value when doing arithmetic. This is done to provide a more deterministic result (than say C, which is less constrained in its specification).

在进行算术运算时,Java 会自动将大小(以位为单位)小于 int 的整数类型“提升”为 int 值。这样做是为了提供更具确定性的结果(比说 C,它的规范约束较少)。

You may want to have a look at this question on casting a 'short'.

你可能想看看这个关于“短”的问题。

回答by Sultan Khan

According to my understanding, you meant

根据我的理解,你的意思是

Integer i=new Integer(2);
byte b=i;   //will not work 

final int i=2;
byte b=i;   //fine 

At last

最后

Byte b=new Byte(2);
int a=b;   //fine

回答by Manish Sakariya

Byte is 8 bit. 8 bit can represent 256 numbers.(2 raise to 8=256)
Now first bit is used for sign. [if positive then first bit=0, if negative first bit= 1]
let's say you want to convert integer 1099 to byte. just devide 1099 by 256. remainder is your byte representation of int
examples
1099/256 => remainder= 75
-1099/256 =>remainder=-75
2049/256 => remainder= 1
reason why? look at this image http://i.stack.imgur.com/FYwqr.png

字节为 8 位。8 位可以表示 256 个数字。(2 升到 8=256)
现在第一位用于符号。[如果正则第一位= 0,如果负第一位= 1]
假设您想将整数 1099 转换为字节。只需将 1099 除以 256。 余数是 int
示例的字节表示
1099/256 => 余数= 75
-1099/256 => 余数=-75
2049/256 => 余数= 1
为什么?看看这张图片http://i.stack.imgur.com/FYwqr.png

回答by MDIT

The following fragment casts an intto a byte. 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.

以下片段将int转换为byte。如果整数的值大于一个byte的范围,它将被减少模(整数除以的余数)byte的范围。

int a;
byte b;
// …
b = (byte) a;