c++ - 从 char 数组转换/提取整数

标签 c++ c bit-manipulation zlib c-strings

我得到一个 cstring,来自 gzread 的调用。我知道数据是 block ,每个 block 由一个 unsigned int、char、int 和 unsigned short int 组成。

所以我想知道将此 cstring 拆分为适当变量的标准方法是什么。

说前4个字节,是一个unsigned int,下一个字节是char,接下来的4个字节是signed int,最后2个字节是unsigned short int。

//Some pseudocode below which would work
char buf[11];
unsigned int a;
char b;
int c;
unsigned short int d;

我想我可以使用适当的偏移量进行 memcpy。

memcpy(&a, buf, sizeof(unsigned int));
memcpy(&b, buf+4, sizeof(char));
memcpy(&c, buf+5, sizeof(int));
memcpy(&d, buf+9, sizeof(unsigned short int));

还是使用一些位运算符更好?就像移动和掩蔽。

或者将所有 11 个字节直接 gzread 到某个结构中会更好,或者这甚至可能吗?结构的内存布局是否固定,这是否适用于 gzread?

最佳答案

如果您打包结构(阅读 __packed__ 属性),您可以依赖顺序并且成员是非对齐的。因此,您可以直接读入结构。但是,我不确定此解决方案的可移植性。

否则,像这样使用指针魔法和转换:

char *buffer;
int a = *(reinterpret_cast<int*> (buffer))
unsigned short b = *(reinterpret_cast<unsigned short*> (buffer + sizeof(int)))

关于c++ - 从 char 数组转换/提取整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7721784/

相关文章:

c - 如何将基于 C 的语言添加到 GCC

java - 您能解释一下当您在两个十六进制链之间使用按位 & 运算符时会发生什么吗?

python - 如何在python中将位数组转换为整数

java - 这个标志到底是什么意思? |=

c++ - 故障管道三个命令 "dmesg|sort|more"c++

c++ - 如何使用 _TCHAR* 作为文件名打开文件? C/C++

c - C 中的线程 1 : EXC_BAD_ACCESS (code=1, 地址=0x0)

c++ - 旋转两个球体

c++ - 将唯一指针传递给模板函数

c - 如何找出 *char 字符串是否以 ".abc"结尾