在 Golang 中 binary.write 的C++等价物是什么?

What is the C++ equivalent of binary.write in Golang?

本文关键字:C++ 等价物 是什么 write Golang binary      更新时间:2023-10-16

我正在C++从事项目,该项目采用了golang项目中的许多想法。
我无法正确理解这个二进制.write是如何从文档中工作的,以及如何在C++中复制它。我在我的项目中被困在这一行。

binary.Write(e.offsets, nativeEndian, e.offset)

e.偏移量的类型为*bytes.Buffer,e.偏移量为uint64

在C++标准库中,通常由您来处理字节序问题。因此,让我们暂时跳过它。如果您只想将二进制数据写入流(如文件),则可以执行以下操作:

uint64_t value = 0xfeedfacedeadbeef;
std::ofstream file("output.bin", ios::binary);
file.write(reinterpret_cast<char*>(&value), sizeof(value));

强制转换是必要的,因为文件流处理char*,但你可以将任何你喜欢的字节流写入其中。

您也可以以这种方式编写整个结构,只要它们是"普通旧数据"(POD)。例如:

struct T {
uint32_t a;
uint16_t b;
};
T value2 = { 123, 45 };
std::ofstream file("output.bin", ios::binary);
file.write(reinterpret_cast<char*>(&value2), sizeof(value2));

使用file.read回读这些东西是类似的,但如前所述,如果你真的关心字节序,那么你需要自己照顾它。

如果您正在处理非 POD 类型(例如std::string),那么您将需要处理更复杂的数据序列化系统。如果需要,有许多选项可以处理此问题。