Bitwise Operations and Shifts

Writes two integers in binary and combines them digit by digit with AND, OR and XOR. It also shifts a left and right by the given amount: one place left doubles the value, one place right halves it and drops the remainder.

Computers hold numbers in binary, using only 0 and 1, with each place worth twice the one to its right. Bitwise operations compare those binary digits one place at a time. Unlike ordinary addition or multiplication, nothing carries from one place to the next. Every position is decided on its own.

The three operations

Take the defaults a = 12 and b = 10. In binary, 12 is 1100 and 10 is 1010.

XOR is also called exclusive or. The easiest way to remember it is that matching digits give 0 and differing digits give 1. A useful consequence is that applying XOR twice with the same number brings back the original value.

Shifting

A shift slides the whole binary number sideways. Shifting 12 one place left in decimal turns it into 120, ten times larger, and by the same reasoning a shift in binary doubles the value.

12 is 1100. Shift it two places left and it becomes 110000, which is 48 in decimal, matching 12×22=4812 \times 2^2 = 48. Shift it two places right and it becomes 11, which is 3, matching 12÷22=312 \div 2^2 = 3.

Digits pushed off the right-hand end are simply discarded. 13 is 1101, and shifting it one place right gives 110, which is 6. The result is not 6.5, because the remainder is dropped.

Where it is used

The common use is packing many yes-or-no settings into a single number. Assign one binary place to each setting, and AND will test whether a particular setting is on, OR will switch one on, and XOR will flip it. Shifts also serve as a quick way to multiply or divide by powers of 2.

Points to watch

This calculator accepts integers from 0 to 2147483647. That upper value is 2 multiplied by itself 31 times, minus 1, and it is the usual limit for bitwise work in many programming languages. When a left shift would push the result past the range of exactly representable whole numbers, the calculator says so rather than returning a wrong figure.