C ++中字节寻址的算法

时间:2017-03-27 09:43:00

标签: c++ algorithm

我有一个“int word [10000]”的int数组。我需要一种方法,使得4个连续数字对应于数组的1个元素。 (字节寻址)

例如:

0, 1 , 2 , 3 refers to word[0]
4, 5 , 6 , 7 refers to word[1]
8 , 9 , 10 , 11 refers to word[2]
.....
396, 397, 398, 399 refers to word[100]

不使用哈希映射或任何其他数据结构。

由于

1 个答案:

答案 0 :(得分:1)

使用

unsigned char *bytes=static_cast<unsigned char*>(word);
unsigned char first=bytes[0];
unsigned char second=bytes[1];

bytes会将word作为10000*sizeof(int)字节数组进行索引,但您似乎已经知道您的平台已sizeof(int)==4

NB 1:sizeof(unsigned char)==1有一条规则。访问字节的最佳方法通常是unsigned char

注意2:您的平台是大端还是小端将确定bytes[0]是否是第一个元素的最小或最重要的字节(依此类推)。