2011-11-17 54 views
3

我想将两个整数值存储到C++中的char数组中。 这里是代码..存储和读取int数据到字符数组

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的值。

我该怎么做?

感谢, 尼克

P.S:我知道这是做这种愚蠢的方式,但相信我,它的约束。

回答

2

我认为,当你写static_cast<char>,该值被转换为1字节字符,因此,如果它不适合在一开始的字符,你会失去数据。

我会做的是使用*((int*)(data+sizeof(int)))*((int*)(data+sizeof(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; 
+0

或'reinterpret_cast'如果您使用命名演员 – Dani

+0

C风格演员不应该再用于C++了,特别是如果您不清楚可能的副作用。 – arne

1

我还没有尝试过,但下面应该工作:

char data[20]; 
int value; 

memcpy(&value,data,sizeof(int)); 
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); 
} 
2

如果AR在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

尝试如下:

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

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