gpt4 book ai didi

c++ - C/C++ 中的读取字节方法

转载 作者:太空宇宙 更新时间:2023-11-03 10:20:26 26 4
gpt4 key购买 nike

我是 C 的新手,我想知道是否有标准的库方法来读取 bytes/int/long如:getChar()、getInt()、getLong()。

例如,如果我调用 getInt(),它将以字符串形式返回 4 个字节并将 char 指针地址移动 4。我在哪里可以找到这些方法?

最佳答案

不,库不直接系统地支持二进制(反)序列化。 read() 函数将移动流指针,但我认为您无法绕过一段依赖于平台的代码来解释字节流:

std::infile thefile("data.bin", "rb");

float f;
double d;
uint32_t i;

// the following is OK and doesn't constitute type punning
char * const pf = reinterpret_cast<char*>(&f);
char * const pd = reinterpret_cast<char*>(&d);
char * const pi = reinterpret_cast<char*>(&i);

// the following may or may not give you what you expect
// Caveat emptor, and add your own platform-specific code here.
thefile.read(pf, sizeof(float));
thefile.read(pd, sizeof(double));
thefile.read(pi, sizeof(uint32_t));

在仅读取无符号整数值的情况下,您可以执行代数提取,这在某种意义上是类型安全的并且只需要您知道序列化数据格式的字节序:

unsigned char buf[sizeof(uint32_t)];
thefile.read(reinterpret_cast<char*>(buf), sizeof(uint32_t));

uint32_t n = buf[0] + (buf[1] << 8) + (buf[2] << 16) + (buf[3] << 24); // little-endian

以二进制形式读取 float 据尤其令人厌烦,因为您必须了解有关数据流的大量额外信息:它是否使用 IEEE754? (你的平台是吗?)什么是字节序(浮点字节序独立于整数字节序)?或者它完全代表其他东西?文件格式的良好文档至关重要。


在 C 语言中,您将使用 fread() 和 C 风格的转换,char * const pf = (char*)(&f)

关于c++ - C/C++ 中的读取字节方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7444464/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com