简体   繁体   中英

Why is the value of this uint32_t -2147483648?

Using gcc compiler, why is this uint32_t -2147483648 when I set the MSB? 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. What you want is %u which is for unsigned integers. printf is not smart enough to guess the type of your data.

Source

printf() doesn't know the type of something you pass it and has to trust you to use the correct conversion specifier . But you don't. With %d , printf() interprets your value as an int .

On a platform where unsigned int is the same as uint32_t (very common), you could use %u instead. But beware this isn't portable, eg to platforms where int only has 16 bits. The correct way to print an uint32_t looks like this (you have to include inttypes.h ):

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

See eg this inttypes.h reference

You are using wrong format specifier here. %d is for int type, ie, signed integer type.

To print exact width variables, you need to use PRIuN macros as format specifiers.

For unsigned type 32 bit, that would be PRIu32 . For an exhaustive list, see chapter §7.8.1, C11 .

Type of var is uint32_t . But you are printing it using %d which is undefined behaviour . Use PRIu32 from <inttypes.h> to print uint32_t :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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