C:未签名的long int行为不符合预期

时间:2019-06-28 14:31:29

标签: c

此代码的行为不符合预期。它只是尝试将unsigned long int中的第31位设置。

int main() {
    printf("sizeof(unsigned long int) is %ld bytes\n", sizeof(unsigned long int));
    unsigned long int v = 1 << 30;
    printf("v is (%lx)\n", v);
    v = 1 << 31;
    printf("v is (%lx)\n", v);
}

以下是输出:

sizeof(unsigned long int) is 8 bytes
v is (40000000)
v is (ffffffff80000000)

有人可以解释吗?也许printf格式有问题?

1 个答案:

答案 0 :(得分:3)

v = 1 << 31;中,1不是unsigned long int。它是int。将其移位31位会溢出int类型(在您的C实现中)。

要获取第31位为1的unsigned long int,应将unsigned long int移31位:v = (unsigned long int) 1 << 31;v = 1ul << 31