2

我有

const uint8_t longByteTable[16][256][16] = { { { 0x00, ... } } };

声明为硬编码八位字节值的三维 16x256x16 数组。

出于优化目的和其他各种原因,我需要将此数组解释为 uint64_t 值的三维 16x256x2 数组:

const uint64_t reinterpretedTable[16][256][2];

我需要的是一种在严格的 ISO/ANSI C中强制转换的有效方法 。这是:longByteTable reinterpretedTable

const uint64_t (*reinterpretedTable)[256][2] = 
    (const uint64_t(*)[256][2])longByteTable;

这样做的正确方法?

PS我不能longByteTable用后一种类型声明,因为那样它不能在不同的字节序下正常工作,我需要为不同的字节序声明不同的表,或者执行一些运行时检查和轮换。是的,重新解释数组的所有进一步转换都是字节顺序不变的。

4

1 回答 1

2

由于 C 的指针别名规则,您不能进行此类转换。唯一安全的方法是使用联合:

typedef union
{
  uint8_t longByteTable[16][256][16]
  uint64_t reinterpretedTable[16][256][2];
} table_t;

const table_t table;

尽管请注意,这仍然会使您的代码依赖于字节序。使代码与字节顺序无关的唯一方法是通过使用位移向/从更大的整数类型分配值。

于 2016-04-06T10:59:07.567 回答