c - 将 (uint32_t) 与硬编码值进行比较是否安全?

标签 c uint32-t

我需要对 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 位 intlong 的系统上是 int > 在具有 16 位 int 的系统上。

(由于这里存在uint32_t,我假设8的二进制补码和CHAR_BIT。此外,我不知道任何系统具有16 位 int64 位 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/

相关文章:

C - Case 语句无法比较变量

c++ - while循环排除条件

c - 如何遍历数组以将它们复制到另一个 uint32_t 类型的数组中?

c++ - 如何通过 wprintf 函数打印 uint32_t 变量值?

c - 是否可以让 ESP8266 在 WPA2 企业网络上运行?

c - 在 C 中的其他输出之间打印数组元素

c - 数组 get 被 while 循环覆盖,它们都具有相同的数据

c++ - 快速将 uint32_t 转换为二进制

python - 如何将 uint32_t 转换为无符号字符数组?

将 uint32_t 转换为网络字节顺序