从未对齐的 uint8_t 读取重铸为 uint32_t 数组 - 未获取所有值 [英] Reading from an unaligned uint8_t recast as a uint32_t array - not getting all values

查看:22
本文介绍了从未对齐的 uint8_t 读取重铸为 uint32_t 数组 - 未获取所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 uint8_t 数组转换为 uint32_t 数组.但是,当我尝试这样做时,我似乎无法访问每连续 4 个字节.

I am trying to cast a uint8_t array to uint32_t array. However, when i try to do this, I cant seem to be able to access every consecutive 4 bytes.

假设我有一个 8 字节的 uint8_t 数组.我想将字节 2 -> 6 作为一个 uint32_t 访问.

Let us say I have a uint8_t array with 8 bytes. I would like to access byte 2 -> 6 as one uint32_t.

这些都得到相同的值*((uint32_t*)&uint8Array[0]), *((uint32_t*)&uint8Array[1]), *((uint32_t*)&uint8Array[2]), *((uint32_t*)&uint8Array[3])

These all get the same value *((uint32_t*)&uint8Array[0]), *((uint32_t*)&uint8Array[1]), *((uint32_t*)&uint8Array[2]), *((uint32_t*)&uint8Array[3])

*((uint32_t*)&uint8Array[4]) 按预期获取字节 4 -> 8.

While *((uint32_t*)&uint8Array[4]) gets the bytes 4 -> 8 as expected.

所以我似乎无法从任何地址访问 4 个连续字节?

So it seem like I can not access 4 consecutive bytes from any address?

有什么办法可以做到吗?

Is there any way that I can do this?

推荐答案

如果你想要字节 2..6,你将不得不结合多个对齐的负载来得到你想要的.

If you want bytes 2..6, you're going to have to combine multiple aligned loads to get what you want.

uint32_t *ptr = ...;
uint32_t value = (ptr[0] >> 16) | (ptr[1] << 16);

从技术上讲,这也是在一般情况下用 C 做事的可移植方式,但我们都被宠坏了,因为您不必在 x86、ARM、Power 上做额外的工作,或其他常见架构.

Technically, this is also the portable way to do things in C in general, but we're all spoiled because you don't have to do the extra work on x86, ARM, Power, or other common architectures.

这篇关于从未对齐的 uint8_t 读取重铸为 uint32_t 数组 - 未获取所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆