如何从C中给定的char指针读取4个字节的数据 [英] How to read 4 bytes of data from a given char pointer in C
问题描述
方案是,我想从给定的char类型的指针中读取4个字节的数据。
例如: -
int a=0;
char* c; // This will have some address
我想做的是从c开始读取4个字节(即地址),然后将其分配给变量a
,这是一个整数。
What i wanna do is read 4 bytes starting from c (i.e. the address) and assign them in variable a
which is an integer.
我的解决方案:
a = *(int*)c; // Assembly is LDR r1, [r6,#0x00]
我的问题:
以上解决方案在某些体系结构上效果很好,但在某些体系结构上却失败。
具体来说,在我的情况下,它在Arm CortexM0上失败。
My Problem:
Above solution works well on some architectures but fails on some.
To be specific, in my case, it fails on Arm CortexM0.
如果有人用任何便携式,高效(最少组装)的方式替换了我解决方案,请分享,这将对我有很大帮助,我在此先感谢您;)
If any one has any portable, highly efficient(with minimum assembly) replacement of my solution please share, it would be a great help to me and I thank you for that in advance ;)
请询问是否需要更多信息。
Please ask if more info needed.
推荐答案
问题可能是由于 alignment 。某些CPU体系结构无法在未对齐的地址上读取或写入非字节值。
The problem could be because of alignment. Some CPU architectures can't read or write non-byte values on unaligned addresses.
解决方案是改为进行未对齐的字节访问,这可以通过< a href = http://en.cppreference.com/w/c/string/byte/memcpy rel = noreferrer> memcpy
:
The solution is to make unaligned byte-access instead, which can easily be done with memcpy
:
memcpy(&a, c, sizeof a);
这篇关于如何从C中给定的char指针读取4个字节的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!