简体   繁体   中英

Width of int64_t, is it always 64 bits?

For the following code

static inline float fix2float(int64_t f)
{
    return (float)f / (1 << 60); // <-- error here
}

The compiler is giving me these warnings.

warning: left shift count >= width of type
warning: division by zero

Why is the compiler giving these warnings when 64 > 60?

1 is not a 64-bit number in your C implementation. It is an int , which is likely 32 bits.

The compiler does not look over an expression and see that there is an int64_t involved, therefore other arithmetic should use 64 bits. It builds up expressions from their parts. In the part (1 << 60) , the compiler recognizes one and gives it a type of int , because that is what the C rules say to do with simple constant values (there are additional rules for hexadecimal notation, suffixes, and large values). So, 1 << 60 tries to shift an int by 60 bits. Since the int on your system is only 32 bits, the compiler warns you.

A better way to write this is return f * 0x1p-60f; . 0x1p-60f is a float constant with value 2 –60 .

In your code there is error not actually related to int64_t. In (1 << 60) expression both 1 and 60 are considered int (which is usually 32 bits). You should use modifier LL . Something like (1LL << 60).

#include <stdio.h>

int main()
{
    printf("%llx\n", (1LL << 60));
    return 0;
}

By the way please pay attention to printf() format. int64_t is actually long long (at least in most cases).

UPDATE: there is community voice that recommends to use somewhat different approach:

printf("%" PRIx64 "\n", (UINT64_C(1) << 60));

The issue here is at least in my area not all compilers properly implement these macros (here is one of possible proofs ). But mainstream compilers should be happy. At least I'd not recommend to mix %lld and 1LL even in GCC (you could try, at least GCC 4.6.3 complains about such mix).

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