|Online Tools » Computers » Bit shifts
Bit shifting involves moving bits one or more steps in either the left or right direction. When the bits are shifted one step the bit that is located furthest in the shift direction will fall away and a new bit will be added at the opposite end. The value of the new bit depends on what type of shift operation is used.
With logical shifts the new bits that are shifted in always get the value zero. It's commonly used with unsigned integers (i.e. integers that can't be negative) or when more interested in the actual bits than the value that they represent.
For positive integers, a step with logical left shift is the same as multiply by two, and a step with logical right shift is the same as integer division by two, so by doing multiple steps it is possible to multiply and divide by 2^n, where n is the number of steps, as long as the result fits in the number of bits that is being used. If a multiplication or a division can be replaced with a shift operation it is often slightly faster for the computer to calculate.
Arithmetic shifts are suitable for signed integers (i.e. integers that can be both positive and negative) that uses two's complement representation for negative numbers.
Arithmetic left shift is identical to logical left shift and can be used in the same way to multiply, both positive and negative values, by two.
With arithmetic right shift new bits get the same value as the sign bit (the leftmost bit). This ensures that the sign (+/−) remains the same before and after. One step with arithmetic right shift is almost the same as integer division by two. The difference is that the result is always rounded down (towards minus infinity) instead of towards zero.
Circular shifts, also called rotations, use the bit that got shifted out at one end and inserts it back as the new bit value at the other end. Circular shifts are often used for cryptographic applications and are suitable when it is desirable to not lose any bit values.
The value of the last bit that got shifted out is normally stored in a carry flag. A special type of circular shift, called rotate through carry, uses the old value of this flag for the bit that is shifted in.
Rotate through carry can be used to shift larger values than the computer can normally handle. For example, if a computer can only perform shifts on 32 bits at a time, but we want to perform an arithmetic right shift on a 64-bit value, we can do the calculations in two steps. First we perform an arithmetic right shift on the half containing the most significant bits. The bit that got shifted out will be stored in the carry flag. To finish the calculation we then perform a rotate through carry operation on the second half.