在Java和C 中的字节数
integer to byte in Java and C++
在我的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 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并分布。
相关文章:
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 基于字节数组生成静态范围整数值
- 将字节数组转换为带有字节序问题的指针
- 使用 stbi_write_png,如何将 0 和 1 的矩形字节数组转换为单色 png 文件?
- 字节数组初始化会导致 DirectX 崩溃
- 使用 swig 追加到字节数组
- C++ 替换字节数组中项的顺序
- QDataStream 读取和写入的字节数比 QFile::length() 报告要多
- 如何从保存在 Java 中C++的字节数组中读取数字?
- 如何在C++(Arduino)中将浮点数组转换为字节数组
- 我正在尝试修改一个字节数组并通过 JNI 将其从 c++ 发送到 java
- 在Java和C 中的字节数
- Java字节数组(长度值)转换为C 的长度
- 异步Boost写入Java套接字-传入的字节数组有时部分为0
- c++和Java字节数组
- 将字节数组转换为java类型
- 如何将cv::MAT字节数组从c++发送到Java中的位图
- 使用JNI将字节数组从Java传递到C++,而不复制
- 存储Cpp中可读的java字节数组
- 将字节数组从java程序发送到c++