将int数据存储到char数组中并读取

4
我正在尝试在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

现在在程序的另一端,我想要反向执行此操作。也就是说,从这个字符数组中,我需要获取time_delay和wakeup_code的值。

我该如何做?

谢谢, Nick

P.S:我知道这是一个愚蠢的做法,但请相信我它是有约束条件的。

5个回答

3
我认为当您编写static_cast<char>时,该值会转换为一个1字节的字符,因此如果它一开始就无法适应一个字符,您将丢失数据。

我会使用*((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_cast - Daniel
在C++中,不应再使用C风格的强制类型转换,特别是如果您不清楚可能产生的副作用。 - arne

3

如果您正在使用PC x86架构,则不存在对齐问题(除了速度),您可以将char *强制转换为int *进行转换:

char data[20];
*((int *)data) = first_int;
*((int *)(data+sizeof(int))) = second_int;

同样的语法也可以用于从data中读取,只需要交换=的位置。

但请注意,这段代码并不可移植,因为有些架构上未对齐的操作可能不仅缓慢,甚至会导致崩溃。

在这些情况下,最好的方法(还可以在data是不同系统之间通信协议的一部分时控制字节序)是逐个字符在代码中显式地构建整数:

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;

1

我没有尝试过,但是以下应该可以工作:

char data[20];
int value;

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

1

请尝试以下方法:

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

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


0
#include <sstream>
#include <string>
int main ( int argc, char **argv) {
    char ch[10];
    int i = 1234;

    std::ostringstream oss;
    oss << i;
    strcpy(ch, oss.str().c_str());

    int j = atoi(ch);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接