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

查看:216
本文介绍了从未对齐的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数组.我想作为一个uint32_t访问字节2-> 6.

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天全站免登陆