简体   繁体   English

c ++中的位移

[英]Bit shifts in c++

I don't understand why this gives me the same answer: 我不明白为什么这给了我同样的答案:

 long long a = 3265917058 >> 24;
 std::cout << a << std::endl; //194

 long long ip = 3265917058;
 long long b = ip >> 24;
 std::cout << b << std::endl; //194

but this don't: 但这不是:

 long long a = (3265917058 << 16) >> 24;
 std::cout << a << std::endl; //240

 long long ip = 3265917058;
 long long b = (ip << 16) >> 24;
 std::cout << b << std::endl; //12757488 - **i want this to be 240 too!**

Update: I want 32bit shift , but how can i 32bit shift a number that is too large for an int variable? 更新:我想要32位移位,但是我怎么能移动一个对于int变量来说太大的数字呢? Update2: My answer is to make unsigned int ip. Update2:我的答案是使unsigned int ip。 Then everything will be ok. 那一切都会好的。

Your literal constant 3265917058 is an int . 你的文字常量3265917058是一个int Add a LL suffix to get the expected behavio(u)r: 添加LL后缀以获得预期的行为(u)r:

long long a = (3265917058LL << 16) >> 24;

3265917058<<16 both sides are int , so the operation will be done in int (32-bits). 3265917058<<16两边都是int ,所以操作将在int (32位)中完成。

You need 3265917058LL<<16 then the left-side will be a long long and the operation will be done with that width ie 64-bits. 你需要3265917058LL<<16然后左侧将是一个long long ,操作将以该宽度完成,即64位。

To get what you ask for: 得到你要求的:

long long ip=3265917058;
long long b= (static_cast<unsigned int>(ip)<<16)>> 24;
std::cout<<b<<std::endl; // 240

Note that the result you will get (240) is not portable. 请注意,您将获得的结果(240)不可移植。 Mathematically, the result should be 12757488. The value 240 is due to truncation, and this is not guaranteed to happen. 在数学上,结果应该是12757488.值240是由于截断,并且不能保证这发生。 For instance, it doesn't happen on systems where int is 64 bits. 例如,它不会发生在int为64位的系统上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM