我试图使用c将3个整数(字节大小为4)逐字节放入字符串字节中。然后,我需要从字符数组中“提取”这些整数,以便对它们执行整数操作。我环顾四周,找不到任何解决办法。我认为这将需要某种类型的指针使用或移动,但我不知道如何编写它。
char str[12]="";
int a;
int b;
int c;
int x;
int y;
int z;
a=5;
b=7;
c=12;我知道int是4个字节。我希望这样做,以便str char数组中包含以下数据。
str = |a1|a2|a3|a4|b1|b2|b3|b4|c1|c2|c3|c4|*我不想这样。str=‘5’,‘7’,‘12’
然后,我需要从字符数组中“提取”整数。
x=str[0-3]; //extracting a
y=str[4-7]; //extracting b
z=str[8-11]; //extracting c在此之后,我应该能够编写x=y+z,x将等于19。
发布于 2013-10-03 09:03:29
这个问题没有很好地提出,所以你得到了不同的答案,这些答案可能解决了你的问题,也可能没有解决。根据我的解释,这里是你需要的:
int i1, i2, i3;
char arr[sizeof(i1)+sizeof(i2)+sizeof(i3)];
memcpy(arr, &i1, sizeof(i1));
memcpy(arr+sizeof(i1), &i2, sizeof(i2));
memcpy(arr+sizeof(i1)+sizeof(i2), &i3, sizeof(i3));请注意,我是有意地明确使用sizeof of (I)而不是仅仅使用"4“。在您所使用的任何环境中,整数都是32位,这是相当安全的,但这更安全,而且严格来说更正确。
发布于 2013-10-03 07:56:32
一种方法是将str作为int数组来处理:
int* istr = reinterpret_cast<int*>(str)然后你可以使用。
istr[0] = a;
istr[1] = b;
istr[2] = c;和
x = istr[0];
y = istr[1];
z = istr[2];发布于 2013-10-03 08:40:06
最简单的解决方案是使用memcpy
int nums[sizeof str / sizeof(int)];
std::memcpy(nums, str, sizeof nums);
// Do work on nums here...reinterpret_cast方法是未定义的行为。
https://stackoverflow.com/questions/19153712
复制相似问题