其他分享
首页 > 其他分享> > c – 从char数组转换/提取int

c – 从char数组转换/提取int

作者:互联网

我有一个cstring,源自gzread的调用.我知道数据是块,每个块由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(&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个字节直接gz到某个结构中会更好,还是可能?是否修复了结构的内存布局,这是否适用于gzread?

解决方法:

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

否则,使用指针魔术和铸造如下:

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

标签:c-3,c-strings,c,bit-manipulation,zlib
来源: https://codeday.me/bug/20190826/1733150.html