I saw someone used 1 << i, sometimes 1 << n. What is this and how can I use it for?
1 Answers
When you think of the value in binary representation, it shifts the value to the left n
times. n
zero digit(s) will be added to the right.
So 1b
becomes 100b
etc if n == 2
.
If you look at it decimally, shifting one time (n==1
) is equivalent to multiplying the value with 2. Shifting two times equals a times 4 operation and so on.
One advantage is that bit shifting can be faster than a "real" integer multiplication.
Also often in computing you will see so called bit fields where each bit toggles on or off something, or otherwise has some special meaning.
For instance on microcontrollers each bit of a register might represent a digital output that is connected to a LED.
There, the notation can be used to create a "mask" that represents that bit number (i
) that the programmer wants to manipulate.
For instance
x &= ~(1<<4)
clears bit number 4, while x |= (1<<4)
would set the same bit.
Be aware that shifting might cause undefined behavior on some systems if i
is too high or if the left side of the operation has a negative value.

- 615
- 7
- 17