2017-03-28 35 views
2
#include <stdio.h> 
#include <stdint.h> 

int main(){ 
    uint64_t a = 1 << 63; 
    /* do some thing */ 
    return 0; 
} 

$ gcc -Wall -Wextra -std=c99 test.c -o test 
warning: left shift count >= width of type [-Wshift-count-overflow] 

问:uint64_t应具有64个比特的宽度,所以左移位运算溢出?如何在C使用uint64_t中

+0

1是'int'文字。使用'1ULL << 63'代替 –

+0

@LưuVĩnhPhúcÇ指定'1'类型的_integer constant_'int'。 C中唯一指定的_literals_是_string literals_和_compound literals_。 '1'既不是那两个文字。 – chux

+0

“为什么左移操作溢出?” - >哪一个首先发生:'1 << 63'或者它赋值给'uint64_t a'?由于'1 << 63'发生第一,它被分配给的类型是无关的'1 << 63'评估。 – chux

回答

6

1是一个int它可能只有32位在您的平台上,或者它可能是64位但签名。

使用(uint64_t)1 << 63到第一投1到64位的无符号整数。 (或者((uint64_t)1) << 63,如果你喜欢)

+0

没有必要投,'1ULL'看起来更好。和'(uint64_t中)1 << 64',因为你比移值的位长 –

+0

@LưuVĩnhPhúc固定,64应该已经63多个调用未定义的行为。 – immibis