我在C中有这个代码(仅供学习):
char x;
uint64_t total = 0;
for(x = 20; x < 30; x++){
total = (((((1 << x) * x) / 64) + 1) * sizeof(uint64_t));
printf("%d - %llu\n", x, total);
}
Run Code Online (Sandbox Code Playgroud)
什么是印刷品:
20 - 2621448
21 - 5505032
22 - 11534344
23 - 24117256
24 - 50331656
25 - 104857608
26 - 218103816
27 - 18446744073625665544
28 - 18446744073575333896
29 - 18446744073508225032
Run Code Online (Sandbox Code Playgroud)
为什么在x> 26时我有那些奇怪的值?我在Ubuntu 10.10 64位上的gcc 4.6.1.
我有点困惑,因为我想unsigned long在我的系统上初始化一个大小为8字节的类型的变量(在我认为的每个现代系统上).当我想分配1 << 63给变量时,我得到一个编译器警告但是数字实际上是0.当我这样做时,1 << 30我得到了预期的结果2 ^ 30 = 1073741824.然而,当我这样做时1 << 31,我得到了2 ^ 64(我认为;实际上这不可能)打印的结果18446744071562067968.
任何人都可以向我解释这种行为吗?
#include <stdio.h>
#include <stdint.h>
int main(){
uint64_t a = 1 << 63;
/* do some thing */
return 0;
}
Run Code Online (Sandbox Code Playgroud)
$ gcc -Wall -Wextra -std=c99 test.c -o test
warning: left shift count >= width of type [-Wshift-count-overflow]
Run Code Online (Sandbox Code Playgroud)
问:uint64_t应该有64位宽,为什么左移操作溢出?
为什么这个代码不给预期值的n = 1000000000000预期value = 1099511627775
虽然代码是给255
long long now = n, count = 0, len = 0;
while (now >= 1) {
count++;
now /= 2;
}
len = (1 << count) - 1;
cout << len;
Run Code Online (Sandbox Code Playgroud)