I think many answers here got it somewhat backwards, including the currently accepted one. The biggest application is in shifting data across byte/word boundaries, which is extensively used in
- extracting and inserting bit patterns
- protocols (insert 5 bits starting from bit 6)
- compression schemes (LZW77 and more)
- data transfer (300 baud modems anyone? 7-bit data + parity)
- arbitrary precision arithmetic
- multiplying/dividing by 2 utilises rotations-through-carry
- multiplying/dividing by other powers of two need the ROL (or ROR)
- scrolling 1-bit graphics horizontally
And the niche applications:
- crc16/32
- ciphers
- non-destructive moving bits to sign bit or to carry for testing
The historical perspective is that shifting was expensive: when one needs to shift say 16 bits left by 3, in chunks of 8 bits (or 128 bits left in chunks of 64 bits), a ROL performs two expensive shifts at the cost of one:
rotate all bits left by 3
hi lo
src = fedcba98|76543210
dst = cba98765|43210---
Notice, that the bits "765" need to be shifted right by 5, while bits "43210" need to be shifted left by 3. This is all accomplished by a single rotation, which put all the right bits to the correct position, even if they are accompanied by the wrong bits, which are recombined by masking, which is an inexpensive operation:
dst_lo = ((src_lo ROL 3) & 0b11111000)
dst_hi = ((src_lo ROL 3) & 0b00000111) | (src_hi << 3)
This extends to bignum shifting, or scrolling a monochrome graphics plane horizontally by arbitrary number of pixels.
This algorithm is so essential, that 80386 included a double-rotate instruction for it.
rol
opcodes when compiling code which tries to compute a rotation with the C operators (i.e.(x << 12) | (x >> 20)
). – Trilateralrol
, I meantrol
(well, could beror
). The rotation opcode. – Trilateral<<
and>>
are shifts. But for a 32-bit valuex
, the whole expression(x << 12) | (x >> 20)
, consisting of two shifts (one left, one right) and a bitwise OR, has the same effect than a rotation of a 32-bit word (here, by 12 bits to the left). C compilers are smart enough to notice it, and compile the complete expression as a singlerol
. – Trilateral