英文:
What is the C++ equivalent of binary.write in Golang?
问题
我正在使用C++开发一个项目,其中采用了许多来自golang项目的思想。我不太理解这个二进制写入函数在文档中的工作原理,也不知道如何在C++中实现它。我在项目中遇到了以下这行代码:
binary.Write(e.offsets, nativeEndian, e.offset)
其中,e.offsets的类型是*bytes.Buffer
,e.offset的类型是uint64
。
英文:
I am working on project in C++ that adopts many ideas from a golang project.
I don't properly understand how this binary.write works from the documentation and how I can replicate it in C++. I am stuck at this line in my project.
binary.Write(e.offsets, nativeEndian, e.offset)
The type of e.offsets is *bytes.Buffer
and e.offset is uint64
答案1
得分: 1
在C++标准库中,处理字节序问题通常由你自己来处理。所以我们暂时跳过这个问题。如果你只是想将二进制数据写入流,比如文件,你可以这样做:
uint64_t value = 0xfeedfacedeadbeef;
std::ofstream file("output.bin", std::ios::binary);
file.write(reinterpret_cast<char*>(&value), sizeof(value));
这里需要进行类型转换,因为文件流处理的是char*
类型,但你可以写入任何字节流。
你也可以以类似的方式写入整个结构体,只要它们是“Plain Old Data”(POD)类型。例如:
struct T {
uint32_t a;
uint16_t b;
};
T value2 = { 123, 45 };
std::ofstream file("output.bin", std::ios::binary);
file.write(reinterpret_cast<char*>(&value2), sizeof(value2));
使用file.read
可以类似地读取这些数据,但是如前所述,如果你真的关心字节序,那么你需要自己处理。
如果你处理的是非POD类型(比如std::string
),那么你将需要处理更复杂的数据序列化系统。如果需要的话,有很多选项可以处理这个问题。
英文:
In C++ standard libs, it is generally up to you to deal with endian concerns. So let's skip that for the time being. If you just want to write binary data to a stream such as a file, you can do something like this:
uint64_t value = 0xfeedfacedeadbeef;
std::ofstream file("output.bin", ios::binary);
file.write(reinterpret_cast<char*>(&value), sizeof(value));
The cast is necessary because the file stream deals with char*
, but you can write whatever byte streams to it you like.
You can write entire structures this way as well so long as they are "Plain Old Data" (POD). For example:
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));
Reading these things back is similar using file.read
, but as mentioned, if you REALLY do care about endian, then you need to take care of that yourself.
If you are dealing with non-POD types (such as std::string
), then you will need to deal with a more involved data serialization system. There are numerous options to deal with this if needed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论