C++中与Golang中的binary.write等效的是什么?

huangapple go评论102阅读模式
英文:

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(&quot;output.bin&quot;, ios::binary);
file.write(reinterpret_cast&lt;char*&gt;(&amp;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(&quot;output.bin&quot;, ios::binary);
file.write(reinterpret_cast&lt;char*&gt;(&amp;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.

huangapple
  • 本文由 发表于 2017年3月7日 00:01:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/42630141.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定