Bit shifts in C ++

I do not 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 is not so:

 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 a 32-bit shift, but how can a 32-bit shift shift a number that is too large for the int variable? Update2: My answer is to make unsigned int ip. Then everything will be fine.

+5
source share
3 answers

Your constant letter 3265917058is this int. Add a suffix LLto get the expected behavior of (u) r:

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

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

You need 3265917058LL<<16, then the left side will be long long, and the operation will be performed with such a width, that is, with 64-bit.

+2

, :

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

Please note that the result you obtained (240) is not portable. Mathematically, the result should be 12757488. A value of 240 is associated with truncation, and this is not guaranteed. For example, this does not happen on systems where int- 64 bits.

+1
source

All Articles