[英]How to convert uint16_t[2N] to uint32_t[N] effectively?
I've got an array of six uint16_t
which is actually three uint32_t
, with the bits in the right order and all. 我有一个六个
uint16_t
的数组实际上是三个uint32_t
,其中的位数顺序正确。 How can I cast the former to the latter as effectively as possible? 如何尽可能有效地将前者投射到后者?
The number of elements in the array is known at compile-time. 数组中的元素数量在编译时是已知的。
Like this perhaps: 也许这样:
uint16_t arr16[6];
uint32_t *parr32 = (uint32_t*)(&arr16);
And now you can use parr32[i]
to refer to elements of the overlayed arr16
array. 现在你可以使用
parr32[i]
来引用重叠的arr16
数组的元素。
On your little-endian machine, your bytes are arranged as 在您的小端机器上,您的字节排列为
b a d c f e h g
etc., so casting a pointer to the first int16_t, which points at a
, to an int32_t*
will give the wrong result (or possibly even crash) since it's in the middle of the first int32_t. 因此,将指向第一个int16_t的指针(指向
a
)转换为int32_t*
会产生错误的结果(甚至可能会崩溃),因为它位于第一个int32_t的中间。 On a big-endian machine, where the bytes are arranged as 在大端机器上,字节排列为
a b c d e f g h
then casting the int16_t*
, which points to a
, to an int32_t*
would yield the right result. 然后将指向
a
的int16_t*
转换为int32_t*
将产生正确的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.