Possible Duplicate:
What is the “<<” operator in C++?
In a piece of code I am looking at, the following takes place:
... (header[4] << 8) + header[5] ...
I’m fairly new to programming and have never seen the << operator before. Googling didn’t provide any results. Any quick pointers would be appreciated!
<<operator shifts the bits to left by N bits where N comes after the operator. In your example the bits at the address ofheader[4]are shifted to left by 8 bits.What this is good for is that it effectively results in multiplication by 256, because 2^8 = 256. If it were a shift to right the value at
header[4]would be divided by 2^8 = 256.Some real bit-level examples:
So in the end, very often a bit shift means either multiplication(shift to left) or division(shift to right) because that’s what it results in. That is, you can actually replace multiplications and divisions by power-of-two values with bit shifts, or replace bitshifts with multiplications. Compilers often prefer replacing multiplications and divisions with number of bit shifts because for the computer shifting the bits is much faster than actually doing real multiplication or division of the values.