C++ 将int数据存储和读取到char数组中

C++ 将int数据存储和读取到char数组中,c++,arrays,char,C++,Arrays,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数据[20]; *数据=静态广播(延时)//延时为int型

我试图在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数据[20];
*数据=静态广播(延时)//延时为int型
*(data+sizeof(int))=静态广播(唤醒码)//唤醒_代码为int类型
现在在程序的另一端,我想反转这个操作。也就是说,从这个char数组中,我需要获得time_delay和wakeup_code的值

我该怎么做

谢谢, 尼克


附言:我知道这是一种愚蠢的方法,但请相信我,这是一种限制。

我没有尝试过,但以下方法应该有效:

char data[20];
int value;

memcpy(&value,data,sizeof(int));

我认为,当您编写
static\u cast
时,该值将转换为1字节字符,因此,如果它不适合一个字符开始,您将丢失数据

我要做的是使用
*((int*)(data+sizeof(int))
*((int*)(data+sizeof(int)))
来读取和写入数组中的int

*((int*)(data+sizeof(int))) = wakeup_code;
....
wakeup_code = *((int*)(data+sizeof(int)));
或者,您也可以写:

reinterpret_cast<int*>(data)[0]=time_delay;
reinterpret_cast<int*>(data)[1]=wakeup_code;
reinterpret\u cast(数据)[0]=延时;
重新解释广播(数据)[1]=唤醒广播代码;
#包括
#包括
int main(int argc,字符**argv){
char-ch[10];
int i=1234;
std::ostringstream oss;

oss如果您使用的是PC x86体系结构,则没有对齐问题(速度除外),您可以将
char*
转换为
int*
,以进行转换:

char data[20];
*((int *)data) = first_int;
*((int *)(data+sizeof(int))) = second_int;
同样的语法也可以通过交换
=
的两边来读取
数据

但是请注意,此代码是不可移植的,因为在某些体系结构中,未对齐的操作可能不仅速度慢,而且实际上是非法的(崩溃)。 在这些情况下,最好的方法(如果
数据
是不同系统之间通信协议的一部分,那么它也可以为您提供端度控制)可能是在代码中一次显式构建一个字符的整数:

first_uint = ((unsigned char)data[0] |
              ((unsigned char)data[1] << 8) |
              ((unsigned char)data[2] << 16) |
              ((unsigned char)data[3] << 24));
data[4] = second_uint & 255;
data[5] = (second_uint >> 8) & 255;
data[6] = (second_uint >> 16) & 255;
data[7] = (second_uint >> 24) & 255;
first_uint=((无符号字符)数据[0]|
((无符号字符)数据[1]>16)和255;
数据[7]=(第二单元>>24)和255;
尝试以下操作:

union IntsToChars {
struct {
int time_delay;
int wakeup_value;
} Integers;
char Chars[20];
};

extern char* somebuffer;

void foo()
{
    IntsToChars n2c;
    n2c.Integers.time_delay = 1;
    n2c.Integers.wakeup_value = 2;
    memcpy(somebuffer,n2c.Chars,sizeof(n2c));  //an example of using the char array containing the integer data
    //...
}

使用这种联合应该消除对齐问题,除非数据被传递到不同架构的机器。

RealTytRask如果使用命名CASTSC样式的转换,在C++中不再真正使用,尤其是如果您对可能的副作用不清楚。
union IntsToChars {
struct {
int time_delay;
int wakeup_value;
} Integers;
char Chars[20];
};

extern char* somebuffer;

void foo()
{
    IntsToChars n2c;
    n2c.Integers.time_delay = 1;
    n2c.Integers.wakeup_value = 2;
    memcpy(somebuffer,n2c.Chars,sizeof(n2c));  //an example of using the char array containing the integer data
    //...
}