我需要对 32 位整数进行逐位操作(确实 represent chars ,但无论如何)。
下面这种代码安全吗?
uint32_t input;
input = ...;
if(input & 0x03000000) {
output = 0x40000000;
output |= (input & 0xFC000000) >> 2;
我的意思是,在“if”语句中,我正在对左侧的 uint32_t 进行按位运算,而在右侧...我不知道!
那么你知道硬编码“0x03000000”的类型和大小(我的意思是它存储了多少字节)吗?
是否有可能某些系统将 0x03000000 视为 int,因此仅在 2 个字节上对其进行编码,这将是灾难性的?
最佳答案
Is the following kind of code safe?
是的,确实如此。
So do you know the type and size (by that I mean on how much bytes is it stored) of hard-coded "0x03000000" ?
0x03000000
在具有 32 位
int
和 long
的系统上是 int
> 在具有 16 位
int
的系统上。
(由于这里存在uint32_t
,我假设8
的二进制补码和CHAR_BIT
。此外,我不知道任何系统具有16 位
int
和 64 位
long
。)
Is it possible that some systems consider 0x03000000 as an int and hence code it only on 2 bytes, which would be catastrophic?
请参阅上面的 16 位
int
系统,0x03000000
是一个 long
并且是 32 位
。 C 中的十六进制常量是第一种可以表示的类型:
int
、无符号整数
、长
、无符号长
、long long
、 >无符号长长
关于c - 将 (uint32_t) 与硬编码值进行比较是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17379660/