Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bit shifts in c++

Tags:

c++

bit-shift

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? Update2: My answer is to make unsigned int ip. Then everything will be ok.

like image 625
Stals Avatar asked Jan 20 '11 12:01

Stals


3 Answers

Your literal constant 3265917058 is an int. Add a LL suffix to get the expected behavio(u)r:

long long a = (3265917058LL << 16) >> 24;
like image 192
Paul R Avatar answered Sep 21 '22 10:09

Paul R


3265917058<<16 both sides are int, so the operation will be done in int (32-bits).

You need 3265917058LL<<16 then the left-side will be a long long and the operation will be done with that width i.e. 64-bits.

like image 37
Adrian Smith Avatar answered Sep 18 '22 10:09

Adrian Smith


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. Mathematically, the result should be 12757488. The value 240 is due to truncation, and this is not guaranteed to happen. For instance, it doesn't happen on systems where int is 64 bits.

like image 25
MSalters Avatar answered Sep 21 '22 10:09

MSalters