存储Cpp中可读的java字节数组
Storing java byte array readable in Cpp
我在java中将结构{int,int,long}存储为字节数组,并在Cpp中将其读取为二进制结构时遇到了一些困难。
我几乎什么都试过了。我最大的成功是我可以正确地读取Long值,但整数是一些随机数。
我害怕词尾,我不知道如何决定哪种语言使用小词尾还是大词尾。有人能告诉我,我如何在java中存储int、long、double等原始类型,并在Cpp中读取它吗?
谢谢你,这真的很有帮助。
编辑:我知道我想如何在C++中阅读:
struct tick {
int x;
int y;
long time;
};
tick helpStruct;
input.open("test_file", ios_base::in | ios_base::binary);
input.read((char*) &helpStruct, sizeof(tick));
在Java中,我尝试了很多方法,最后一次尝试是:
DataOutput stream = new DataOutputStream(new FileOutputStream(new File("test_file")));
byte[] bytes = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(1).array();
for (byte b : bytes) {
stream.write(b);
}
但是Java代码是开放的。
您只写了第一个整数。。你从来没有写过第二个然后是长的。。因此,你读到的任何值当然都是随机的。请记住,C++中的sizeof(long)
实际上可能不像java中那样是8!另外,不要忘记C++中的结构可能是填充的,最好一次将每个值读取到结构的字段中。
这很管用。。
在java方面:
package test;
import java.io.*;
import java.nio.*;
public class Test {
public static void main(String[] args) throws FileNotFoundException, IOException {
DataOutput stream = new DataOutputStream(new FileOutputStream(new File("C:/Users/Brandon/Desktop/test_file.dat")));
int sizeofint = 4;
int sizeoflong = 4;
ByteBuffer buffer = ByteBuffer.allocate(sizeofint + sizeofint + sizeoflong).order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(5).putInt(6).putInt(7);
byte[] bytes = buffer.array();
for (byte b : bytes) {
stream.write(b);
}
}
}
在C++方面:
#include <fstream>
#include <iostream>
struct tick
{
int x;
int y;
long time;
};
int main()
{
std::fstream file("C:/Users/Brandon/Desktop/test_file.dat", std::ios::in | std::ios::binary);
if (file.is_open())
{
tick t = {0};
file.read(reinterpret_cast<char*>(&t), sizeof(t));
file.close();
std::cout<<t.x<<" "<<t.y<<" "<<t.time<<"n";
}
}
结果为:5 6 7
。
这样做可能更好:
file.read(reinterpret_cast<char*>(&t.x), sizeof(t.x));
file.read(reinterpret_cast<char*>(&t.y), sizeof(t.y));
file.read(reinterpret_cast<char*>(&t.time), sizeof(t.time));
相关文章:
- 在java中读取c++字节的位字段
- 如何从保存在 Java 中C++的字节数组中读取数字?
- 如何在 c++ 中读取用 utf-8 编码的 java unicode 字节字符串
- 我正在尝试修改一个字节数组并通过 JNI 将其从 c++ 发送到 java
- java 输入流,字节大,然后是 127
- C /OPENSL从编码字节(由Java编码)获取RSA键
- 使用C 修改Java方法/字节码
- 在Java和C 中的字节数
- Java字节数组(长度值)转换为C 的长度
- 在java中将两个字节(一个正字节和另一个负字节)合并为短字节
- 如何将状态和字节[]从C++返回到Java
- 如何从java传递给jni的字节缓冲区中进行写和读
- Java字节与C 字节
- 将 java 字符串作为 c/c++ 字节发送
- 将本机uint8_t(Java 字节)转换为整数
- 将Java转换为Symbian C/C++ - 字节和对象数组
- c++和Java字节数组
- SWIG将const unsigned char example[]包装成Java字节[]作为参数
- Java字节设置操作中的字节出现符号(+/-)错误
- 存储Cpp中可读的java字节数组