我有
const uint8_t longByteTable[16][256][16] = { { { 0x00, ... } } };
声明为硬编码八位字节值的三维 16x256x16 数组。
出于优化目的和各种其他原因,我需要将此数组解释为 uint64_t 值的三维 16x256x2 数组:
const uint64_t reinterpretedTable[16][256][2];
我需要的是一种有效的方式来转换 longByteTable
到 reinterpretedTable
在严格的ISO/ANSI C。这是:
const uint64_t (*reinterpretedTable)[256][2] =
(const uint64_t(*)[256][2])longByteTable;
正确的方法吗?
附注我无法使用后一种类型声明 longByteTable
,因为这样它就无法在不同的字节序下正常工作,并且我要么需要为不同的字节序声明不同的表,要么执行一些运行时检查和旋转。是的,重新解释的数组的所有进一步转换都是字节序不变的。
最佳答案
由于 C 的指针别名规则,您无法进行此类强制转换。唯一安全的方法是使用 union :
typedef union
{
uint8_t longByteTable[16][256][16]
uint64_t reinterpretedTable[16][256][2];
} table_t;
const table_t table;
但请注意,这仍然会使您的代码依赖于字节顺序。使代码字节顺序独立的唯一方法是通过使用位移位将值分配给较大的整数类型或从较大的整数类型分配值。
关于将多维数组转换为另一种类型的多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36448619/