问题描述
C/C ++中是否有一种方法可以在任何位置将char数组强制转换为int?
Is there a way in C/C++ to cast a char array to an int at any position?
我尝试了以下操作,如果我尝试使用具有非const偏移量的指针算术,则它会自动对齐到最接近的32位(在32位体系结构上):
I tried the following, bit it automatically aligns to the nearest 32 bits (on a 32 bit architecture) if I try to use pointer arithmetic with non-const offsets:
unsigned char data[8];
data[0] = 0; data[1] = 1; ... data[7] = 7;
int32_t p = 3;
int32_t d1 = *((int*)(data+3)); // = 0x03040506 CORRECT
int32_t d2 = *((int*)(data+p)); // = 0x00010203 WRONG
更新:
- 如评论中所述,输入为3的元组,而我不能改变它.
- 我想将3个值转换为一个int以作进一步处理处理,并且此转换应尽可能快.
- 解决方案不必是跨平台的.我正在与一个非常特定的编译器和处理器,因此可以假定它是32具有大字节序的位架构.
- 结果的最低字节对我来说无关紧要(请参阅上文).
此刻我的主要问题是:为什么d1正确,但d2没有正确?其他编译器也是如此吗?这种行为可以改变吗?
My main questions at the moment are: Why has d1 the correct value but d2 does not? Is this also true for other compilers? Can this behavior be changed?
推荐答案
不,您不能以可移植的方式做到这一点.
No you can't do that in a portable way.
在C和C ++中,尝试将 char *
强制转换为 int *
时遇到的行为都是未定义您已经发现: int
可能在4个字节的边界上对齐,并且 data
当然是连续的.)
The behaviour encountered when attempting a cast from char*
to int*
is undefined in both C and C++ (possibly for the very reasons that you've spotted: int
s are possibly aligned on 4 byte boundaries and data
is, of course, contiguous.)
( data + 3
有效但 data + p
无效的事实可能是由于编译时间与运行时评估所致.)
(The fact that data+3
works but data+p
doesn't is possibly due to to compile time vs. runtime evaluation.)
还请注意,在C或C ++中均未指定 char
的签名,因此您应使用 signed char
或 unsigned char
如果您正在编写这样的代码.
Also note that the signed-ness of char
is not specified in either C or C++ so you should use signed char
or unsigned char
if you're writing code like this.
您最好的选择是使用按位移位运算符(>>
和<<
)以及逻辑 |
和&
将 char
的值吸收到 int
中.如果您要构建具有16或64位 int
s的目标,还可以考虑使用 int32_t
.
Your best bet is to use bitwise shift operators (>>
and <<
) and logical |
and &
to absorb char
values into an int
. Also consider using int32_t
in case you build to targets with 16 or 64 bit int
s.
这篇关于如何在不对齐的位置将char数组转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!