从char数组的末尾读取4个字节

时间:2014-07-25 21:21:39

标签: c++ arrays binary byte reinterpret-cast

如果我有一个char *数组:

char* c = getBytesFromSomewhere();

我想将最后4个字节读取到uint然后读取前4个字节等。我试过这个:

char* end = &c[size-5];

获取指向数组中最后4个字节的指针,然后:

unsigned int n = *(reinterpret_cast<int *>(end));

但它似乎没有起作用......我做错了什么?

2 个答案:

答案 0 :(得分:5)

假设返回的数组大小为8,它在内存中看起来像这样:

+---+
| c |
+---+
  |
  v
  +---+---+---+---+---+---+---+---+
  | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
  +---+---+---+---+---+---+---+---+

(里面的数字是索引。)

现在,如果您将新变量e指向c + size,它将指向超出数据末尾的变量:

+---+                           +---+
| c |                           | e |
+---+                           +---+
  |                               |
  v                               v
  +---+---+---+---+---+---+---+---+
  | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
  +---+---+---+---+---+---+---+---+

如果从1中减去e,它现在指向索引7

+---+                       +---+
| c |                       | e |
+---+                       +---+
  |                           |
  v                           v
  +---+---+---+---+---+---+---+---+
  | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
  +---+---+---+---+---+---+---+---+

如果你减去两个(总共)e将指向索引6,减去3e将指向索引5并减去4,指向的索引为4。如果您减去5,指针e将指向索引3

+---+       +---+
| c |       | e |
+---+       +---+
  |           |
  v           v
  +---+---+---+---+---+---+---+---+
  | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
  +---+---+---+---+---+---+---+---+

这不是最后的四个字节,从最后开始是五个字节。

所以你应该这样做。

char* end = c + size - 4;  /* Subtract by 4 and not 5 */

如果数据来自其他系统,您还应该注意endianness,例如通过互联网。

答案 1 :(得分:0)

在下面的代码中我这样做:

char* end = (c + strlen(c) - 5);
unsigned int tst = 0;
tst = c[0];
tst = ((tst << 8) | c[1]);
tst = ((tst << 8) | c[2]);
tst = ((tst << 8) | c[3]);