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;
l开发者_如何转开发ong 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.
Your literal constant 3265917058
is an int
. Add a LL
suffix to get the expected behavio(u)r:
long long a = (3265917058LL << 16) >> 24;
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.
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.
精彩评论