简体   繁体   English

为什么此uint32_t的值为-2147483648?

[英]Why is the value of this uint32_t -2147483648?

Using gcc compiler, why is this uint32_t -2147483648 when I set the MSB? 使用gcc编译器,为什么在设置MSB时此uint32_t -2147483648? It's unsigned - shouldn't it be positive? 它没有签名-不应该是肯定的吗?

#include <stdio.h>
#include <stdint.h>

#define BIT_SET(a,b) ((a) |= (1<<(b)))

int main()
{
    uint32_t var = 0;
    BIT_SET(var, 31);

    printf("%d\n", var); //prints -2147483648

    return 0;
}

%d is for signed integers. %d用于带符号整数。 What you want is %u which is for unsigned integers. 您想要的是%u ,它用于无符号整数。 printf is not smart enough to guess the type of your data. printf不够聪明 ,无法猜测您的数据类型。

Source 资源

printf() doesn't know the type of something you pass it and has to trust you to use the correct conversion specifier . printf()不知道您传递的内容的类型,必须信任您使用正确的转换说明符 But you don't. 但是你没有。 With %d , printf() interprets your value as an int . 使用%dprintf()会将您的值解释为int

On a platform where unsigned int is the same as uint32_t (very common), you could use %u instead. unsigned intuint32_t (非常常见)相同的平台上,可以改用%u But beware this isn't portable, eg to platforms where int only has 16 bits. 但是请注意,这不是可移植的,例如,在int只有16位的平台上。 The correct way to print an uint32_t looks like this (you have to include inttypes.h ): 打印uint32_t的正确方法如下所示(您必须包含inttypes.h ):

printf("%" PRIu32 "\n", var);

See eg this inttypes.h reference 请参见例如inttypes.h参考

You are using wrong format specifier here. 您在此处使用了错误的格式说明符。 %d is for int type, ie, signed integer type. %d用于int类型,即有符号整数类型。

To print exact width variables, you need to use PRIuN macros as format specifiers. 要打印精确的宽度变量,您需要使用PRIuN宏作为格式说明符。

For unsigned type 32 bit, that would be PRIu32 . 对于32位无符号类型, PRIu32 For an exhaustive list, see chapter §7.8.1, C11 . 有关详细列表,请参见第7.8.1节C11

Type of var is uint32_t . var类型是uint32_t But you are printing it using %d which is undefined behaviour . 但是您正在使用%d打印它,这是未定义的行为 Use PRIu32 from <inttypes.h> to print uint32_t : 使用<inttypes.h> PRIu32打印uint32_t

printf("%"PRIu32"\n",var);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM