gpt4 book ai didi

java - 我们可以在Java中制作无符号字节吗

转载 作者:行者123 更新时间:2023-12-01 19:24:10 24 4
gpt4 key购买 nike

我正在尝试将有符号字节转换为无符号字节。问题是我收到的数据是无符号的,而 Java 不支持无符号字节,因此当它读取数据时,它会将其视为有符号的。

我尝试通过从 Stack Overflow 获得的以下解决方案对其进行转换。

public static int unsignedToBytes(byte a)
{
int b = a & 0xFF;
return b;
}

但是当再次将其转换为字节时,我得到相同的签名数据。我试图将此数据用作仅接受字节作为参数的 Java 函数的参数,因此我不能使用任何其他数据类型。我该如何解决这个问题?

最佳答案

事实上,Java 中的原语是有符号的,这与它们在内存/传输中的表示方式无关——一个字节只是 8 位,是否将其解释为有符号范围取决于您。没有神奇的标志可以说“这是已签名的”或“这是未签名的”。

由于原语经过签名,Java 编译器将阻止您将高于 +127 的值分配给字节(或低于 -128)。但是,没有什么可以阻止您向下转换 int (或短整型)以实现此目的:

int i = 200; // 0000 0000 0000 0000 0000 0000 1100 1000 (200)
byte b = (byte) 200; // 1100 1000 (-56 by Java specification, 200 by convention)

/*
* Will print a negative int -56 because upcasting byte to int does
* so called "sign extension" which yields those bits:
* 1111 1111 1111 1111 1111 1111 1100 1000 (-56)
*
* But you could still choose to interpret this as +200.
*/
System.out.println(b); // "-56"

/*
* Will print a positive int 200 because bitwise AND with 0xFF will
* zero all the 24 most significant bits that:
* a) were added during upcasting to int which took place silently
* just before evaluating the bitwise AND operator.
* So the `b & 0xFF` is equivalent with `((int) b) & 0xFF`.
* b) were set to 1s because of "sign extension" during the upcasting
*
* 1111 1111 1111 1111 1111 1111 1100 1000 (the int)
* &
* 0000 0000 0000 0000 0000 0000 1111 1111 (the 0xFF)
* =======================================
* 0000 0000 0000 0000 0000 0000 1100 1000 (200)
*/
System.out.println(b & 0xFF); // "200"

/*
* You would typically do this *within* the method that expected an
* unsigned byte and the advantage is you apply `0xFF` only once
* and than you use the `unsignedByte` variable in all your bitwise
* operations.
*
* You could use any integer type longer than `byte` for the `unsignedByte` variable,
* i.e. `short`, `int`, `long` and even `char`, but during bitwise operations
* it would get casted to `int` anyway.
*/
void printUnsignedByte(byte b) {
int unsignedByte = b & 0xFF;
System.out.println(unsignedByte); // "200"
}

关于java - 我们可以在Java中制作无符号字节吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59327148/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com