繁体   English   中英

Java中的无符号字节

[英]Unsigned Bytes in Java

默认情况下,Java中的字节是签名的。 我在其他帖子上看到,使用无符号字节的解决方法类似于: int num = (int) bite & 0xFF

有人可以向我解释为什么会这样,并将有符号的字节转换为无符号字节,然后转换为相应的整数? ANDing与11111111个结果相同的字节一个字节-对吗?

类型转换的优先级高于&运算符。 因此,您首先要转换为int,然后进行AND运算以屏蔽所有设置的高位,包括java使用的两个补码表示法的“符号位”,只留下正值原始字节。 例如:

let byte x = 11111111 = -1
then (int) x = 11111111 11111111 11111111 11111111
and x & 0xFF = 00000000 00000000 00000000 11111111 = 255

并且您已经有效地从原始字节中删除了该符号。

用11111111对一个字节进行AND运算得到相同的字节 - 对吗?

除非您与00000000000000000000000011111111进行AND运算,因为0xFF是一个int文字 - Java中没有byte文字。 所以会发生的是, byte被提升为int (类型转换是不必要的),其符号被扩展(即保持byte的可能负值,但是然后通过使用所有这些零进行AND运算来恢复符号扩展。结果是一个int是作为其最显著位完全前者byte ,因此该值byte将不得不为它的无符号。

在Java 8中,这种方法出现在Byte类中:

/**
 * Converts the argument to an {@code int} by an unsigned
 * conversion.  In an unsigned conversion to an {@code int}, the
 * high-order 24 bits of the {@code int} are zero and the
 * low-order 8 bits are equal to the bits of the {@code byte} argument.
 *
 * Consequently, zero and positive {@code byte} values are mapped
 * to a numerically equal {@code int} value and negative {@code
 * byte} values are mapped to an {@code int} value equal to the
 * input plus 2<sup>8</sup>.
 *
 * @param  x the value to convert to an unsigned {@code int}
 * @return the argument converted to {@code int} by an unsigned
 *         conversion
 * @since 1.8
 */
public static int toUnsignedInt(byte x) {
    return ((int) x) & 0xff;
}

如您所见,结果是int而不是字节

它是如何工作的,比方说我们有一个byte b = -128; ,这表示为1000 0000 ,那么当您执行生产线时会发生什么? 让我们使用temp int,比如说:
int i1 = (int)b; i1现在是-128,这实际上用二进制表示,如下所示:

1111 1111 1111 1111 1111 1111 1000 0000

那么i1 & 0xFF在二进制文件中是什么样的?

1111 1111 1111 1111 1111 1111 1000 0000
&
0000 0000 0000 0000 0000 0000 1111 1111

结果

0000 0000 0000 0000 0000 0000 1000 0000

这正好是128,这意味着您的签名值转换为无符号。

编辑
Convertint byte -128 .. 1270 .. 255

int unsignedByte = 128 + yourByte;

您不能通过使用字节来表示值128到255,您必须使用其他东西,如int或smallint。

是的,但是这样你可以确定你永远不会得到一个> 255或<0的数字。

如果第一位为1,则该数字为负。 如果将byte转换为int,如果为负,则将预先设置为1个字节,如果为正,则为0个字节。 运行和例程将丢弃第一个8的剩余字节。这实际上增加了256个负字节。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM