尝试这个:
#include <iostream>
int main()
{
long long num=0x7fffffff00000000ll >> 32;
// ^^
// Literals are by default int
// need to add ll to let the compiler
// know it is long long
for(int i=63; i>=0 ;--i)
{
long long mask = (1ll << i);
// ^^ Note here I want this to be a long long
// before I start shifting it.
std::cout << ((num & mask)?1:0);
}
std::cout << "\n";
return 0;
}
./a.out
0000000000000000000000000000000001111111111111111111111111111111
查看您的代码:
cout<<(((1<<63)+1)&(/*(long long)*/1<<i)?"1":"0");
里面有一个常数:
int val = (1<<63)+1;
// since these are all integer literals (and I am guessing your platform is 32 bit)
0x00000001 or 000000000000000000000000000000001
因此,当您使用该表达式的第二部分循环它时:
/*(long long)*/1<<i
在 i > 32 之后,结果是未定义的,但看起来它正在环绕该位并重新开始。所以你正在设置
10000000000000000000000000000000100000000000000000000000000000001
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Mask bit wrapped around
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The mask on 0x00000001