将 int 数据存储和读取到 char 数组中
我正在尝试将两个整数值存储到 C++ 中的 char 数组中。 这是代码。
char data[20];
*data = static_cast <char> (time_delay); //time_delay is of int type
*(data + sizeof(int)) = static_cast<char> (wakeup_code); //wakeup_code is of int type
现在在程序的另一端,我想反转此操作。也就是说,从这个char数组中,我需要获取time_delay和wakeup_code的值。
我怎样才能做到这一点?
谢谢, Nick
P.S:我知道这是一种愚蠢的方法,但相信我,这是一个限制。
I am trying to store two integer value into an char array in C++.
Here is the code..
char data[20];
*data = static_cast <char> (time_delay); //time_delay is of int type
*(data + sizeof(int)) = static_cast<char> (wakeup_code); //wakeup_code is of int type
Now on the other end of the program, I want to reverse this operation. That is, from this char array, I need to obtain the values of time_delay and wakeup_code.
How can I do that??
Thanks,
Nick
P.S: I know this is a stupid way to do this, but trust me its a constraint.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为当您编写
static_cast
时,该值会转换为 1 字节字符,因此如果它不适合开始时的字符,您将丢失数据。我要做的是使用
*((int*)(data+sizeof(int)))
和*((int*)(data+sizeof(int))) 用于读取和写入整数到数组。
或者,你也可以这样写:
I think when you write
static_cast<char>
, that value is converted to a 1-byte char, so if it didn't fit in a char to begin with, you'll lose data.What I'd do is use
*((int*)(data+sizeof(int)))
and*((int*)(data+sizeof(int)))
for both reading and writing ints to the array.Alternatively, you might also write:
如果您使用的是 PC x86 架构,则不存在对齐问题(速度除外),您可以将
char *
转换为int *
来进行转换:并且只需交换
=
的两边即可使用相同的语法来读取data
。但请注意,此代码不可移植,因为在某些体系结构中,未对齐的操作可能不仅很慢,而且实际上是非法的(崩溃)。
在这些情况下,最好的方法可能是在代码中显式构建整数,一次一个字符:
If you are working on a PC x86 architecture then there are no alignment problems (except for speed) and you can cast a
char *
to anint *
to do the conversions:and the same syntax can be used for reading from
data
by just swapping sides of=
.Note however that this code is not portable because there are architectures where an unaligned operation may be not just slow but actually illegal (crash).
In those cases probably the nicest approach (that also gives you endianness control in case
data
is part of a communication protocol between different systems) is to build the integers explicitly in code one char at a time:我还没有尝试过,但以下应该有效:
I haven't tried it, but the following should work:
尝试以下操作:
使用此类联合应该可以消除对齐问题,除非数据传递到具有不同体系结构的机器。
Try the following:
Using such union should eliminate the alignment problem, unless the data is passed to a machine with different architecture.