存储在字符数组一个int? [英] Store an int in a char array?

查看:160
本文介绍了存储在字符数组一个int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要存储一个4字节INT在字符数组......使得字符数组的前4的位置是4个字节的int。

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...

此外,奖励积分,如果有人可以给我code在一个循环做这个... 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...

EDIT2:请不要计较字节顺序......我会担心字节顺序。我只是想不同的方式来acheive以上的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

EDIT3:如果您不能告诉,我试着写上较低的一个序列化类...所以我在寻找不同的策略序列化一些常见的数据类型。

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.

推荐答案

不是最优化的方式,但端安全的。

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆