在Java和C 中的字节数

integer to byte in Java and C++

本文关键字:字节数 Java      更新时间:2023-10-16

在我的C 代码中,我需要转换一个int并将其放入字节中。我代表使用char的字节。在我的Java代码中,我应该阅读此byte(它是通过网络发送的),我应该从该字节(我发送的一个)中获取适当的int

我应该提到这个字节少于15,因此一个字节足以容纳它

但是,Java代码在某些尝试中读取负数,当我尝试其他方式时,它给了我完全不同的数字。我怀疑这是一个大/小恩迪安的问题。

我尝试了什么:

// C++
char bytes[255];
bytes[0] = myInt; // attempt 1
bytes[0] = myInt & 0xFF; // attempt 2
// ... send the byte array over the network
// JAVA
// receive the byte
int readInt = bytes[0]; //attempt 1
int readInt = bytes[0] & 0xFF; // attempt2

鉴于两个应用程序(C 侧和Java侧)将在同一台Ubuntu机器上运行?

注意:这是从不一个endian问题。只有当您工作低级别或制作自己的字节数组代表一个数字时,这可能是一个问题。

现在只是一个字节,所以没有endian问题。

尝试使用未签名的int。

进一步编辑:int readInt = bytes[0] & 0xFF应该起作用。

for (int i = 0; i < 256; i++) {
    byte b = (byte) i;
    int j = b & 0xFF;
    System.out.println("The byte is " + b + " and the int is " + j);
}

给出:

The byte is 0 and the int is 0
The byte is 1 and the int is 1
...
The byte is 126 and the int is 126
The byte is 127 and the int is 127
The byte is -128 and the int is 128
The byte is -127 and the int is 129
...
The byte is -2 and the int is 254
The byte is -1 and the int is 255

编辑(在上面的评论之后):7 = 0000 0111 and -32 = 1110 0000 (= 224 as int)问题似乎是某种镜像翻转。

170 = 1010 1010 (= -86 as Java byte)对我来说没有意义,因为3个位上的3变成4并分布。