integer operations with <<
I've recently bee seen a number of code examples with stuff like
1 << 20
although I knew this operator could be used on integers I'm not sure what it does and every google search I tr开发者_C百科y doing on it returns stuff about cout <<
but nothing on the integer operations. Could someone tell me what this operator does to integers?
<<
is Bit wise left shift operator
C++03 [5.8/2
]
The value of E1 << E2 is E1 (interpreted as a bit pattern) left-shifted E2 bit positions; vacated bits are zero-filled. If E1 has an unsigned type, the value of the result is E1 multiplied by the quantity 2 raised to the power E2, reduced modulo ULONG_MAX+1 if E1 has type unsigned long, UINT_MAX+1 otherwise. [Note: the constants ULONG_MAXand UINT_MAX are defined in the header ). ]
In addition in the expression E1 << E2
if E1
has a signed type and negative value the behaviour is undefined.
That means something like -1 << 4
invokes UB.
Bit shifting: http://en.wikipedia.org/wiki/Bitwise_shift#Bit_shifts
You are shifting 1 20 bits left, or...
1 << 20 == (binary) 1 0000 0000 0000 0000 0000 == 2^20 == 1048576
The use of << and >> for io is actually newer than their "original" purpose, bit shifting.
1 << 1
means to take the binary 1 (which is also just plain 1) and move everything along 1 to the left, resulting in a binary 10 or 2. It doubles it. 1 << 2
becomes 4, 1 << 3
becomes 8, and so on. (Starting with a more complicated number than 1 still works, again you just shift everything over to the left.) This kind of work is called "bit twiddling" by some. It can save time for certain kinds of arithmetical operations.
精彩评论