问题描述
我想将一个 4 字节的 int 存储在一个 char 数组中...这样,char 数组的前 4 个位置就是 int 的 4 个字节.
I want to store a 4-byte int in a char array... such that the first 4 locations of the char array are the 4 bytes of the int.
然后,我想将 int 从数组中拉回来...
Then, I want to pull the int back out of the array...
此外,如果有人可以给我在循环中执行此操作的代码,则奖励积分...... IE 将 8 个整数写入 32 字节数组.
Also, bonus points if someone can give me code for doing this in a loop... IE writing like 8 ints into a 32 byte array.
int har = 0x01010101;
char a[4];
int har2;
// write har into char such that:
// a[0] == 0x01, a[1] == 0x01, a[2] == 0x01, a[3] == 0x01 etc.....
// then, pull the bytes out of the array such that:
// har2 == har
谢谢各位!
假设 int
是 4 个字节...
Assume int
are 4 bytes...
请不要关心字节序……我会担心字节序.我只想用不同的方法在 C/C++ 中实现上述目标.谢谢
Please don't care about endianness... I will be worrying about endianness. I just want different ways to acheive the above in C/C++. Thanks
如果你不知道,我正在尝试在低级别编写一个序列化类......所以我正在寻找不同的策略来序列化一些常见的数据类型.
If you can't tell, I'm trying to write a serialization class on the low level... so I'm looking for different strategies to serialize some common data types.
推荐答案
不是最优的方式,但是是 endian 安全的.
Not the most optimal way, but is endian safe.
int har = 0x01010101;
char a[4];
a[0] = har & 0xff;
a[1] = (har>>8) & 0xff;
a[2] = (har>>16) & 0xff;
a[3] = (har>>24) & 0xff;
这篇关于将 int 存储在 char 数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!