Binary, two's complement and the bit operators

Video lessonComing soon

1 A number is a row of bits

Some questions about a number are awkward with ordinary arithmetic. Is n a power of two? In how many places do 12 and 10 differ?

The computer stores every integer as a row of bits, each 0 or 1. A few operators work on that row directly, on all its bits in one step.

We write numbers in base 10. Each place is worth ten times the place to its right. Binary is base 2. Each place is worth twice the place to its right, and each box holds 0 or 1.

310001051
305 in base 10: 300 + 5
012806413201618140201
44 in binary: 32 + 8 + 4

To read binary, we add up the place values of the boxes that hold 1. Here that is 32 + 8 + 4 = 44, so 44 is 00101100 in binary. It is our example through the whole lesson.

Bits are numbered from the right, starting at 0, and bit i is worth 2ⁱ. Bit 0 is the lowest bit. It is the only odd place value, so it is 1 exactly when the number is odd.

An int has 32 bits. The drawings use 8, so they stay readable, and the rules are the same at any width.

2 Decimal to binary and back

To turn a number into binary, we read its lowest bit and drop it, again and again. It is the loop from the lesson on extracting digits, with 2 in place of 10:

  • n % 2 is the lowest bit. It is 0 for an even number and 1 for an odd one.
  • n / 2 drops the lowest bit. Every other bit moves one place to the right.

The bits come out from the right, so each new bit goes in front of the ones we have:

nn % 2bits so farn / 2
440022
2200011
1111005
5111002
20011001
111011000

The loop stops at 0 with 101100. The two leading 0s of 00101100 add nothing, so it leaves them out.

To go back, we read the bits from the left. Each bit doubles the value so far and adds itself. For 101100, the value goes 1, 2, 5, 11, 22, 44. That is the n column of the table, read from the bottom up.

Every tab turns 44 into 101100, and 101100 back into 44. Each loop takes one turn per bit. A number n has about log₂ n bits, so each conversion is O(log n). Even 10⁹ has only 30 bits.

C++

Printing bits. bitset<8>(44).to_string() gives 00101100, with the leading 0s. It is handy for checking work by hand, and it shows a negative number's bits too.

Printing bits. Integer.toBinaryString(44) gives 101100. For a negative int, it prints all 32 bits.

Printing bits. format(44, "08b") gives 00101100, and bin(44) gives 0b101100. A negative number prints with a minus sign, not its bits: bin(-44) is -0b101100.

Printing bits. (44).toString(2) gives 101100. A negative number prints with a minus sign. (-44 >>> 0).toString(2) shows its 32 bits.

Printing bits. fmt.Sprintf("%08b", 44) gives 00101100. A negative int prints with a minus sign. To see its 32 bits, print uint32(n) instead.

Printing bits. format!("{:08b}", 44) gives 00101100. A negative i32 prints all 32 of its bits.

Printing bits. Convert.ToString(44, 2) gives 101100. For a negative int, it prints all 32 bits.

3 Negative numbers: two's complement

Eight boxes with place values from 128 down to 1 hold 0 to 255. No negative number fits. Two's complement changes one thing: the top box is worth −128 instead of 128.

1−12816413211618141211
All ones: −128 + 127 = −1

The other seven boxes add up to at most 127. So a 1 in the top box makes the number negative, and the top bit is the sign bit. Three patterns are worth knowing:

  • 11111111 is −1. The seven small boxes make 127, and −128 + 127 = −1.
  • 10000000 is −128, the smallest value.
  • 01111111 is 127, the largest.

So 8 bits hold −128 to 127. A 32-bit int holds −2³¹ to 2³¹ − 1, about ±2.1 × 10⁹. One past the top wraps round to the bottom: 127 + 1 gives 10000000, which is −128.

sign bit 1sign bit 0−128−1127
8 bits hold −128 to 127. Adding 1 to 127 wraps round to −128

This design lets the computer add negative numbers the same way as positive ones. In −1 + 1, the carry runs through all eight 1s and falls off the top. That leaves 00000000, which is 0.

To negate a number, we flip every bit and add 1:

−x = ~x + 1

The reason is short. A number x and its flip ~x never have a 1 in the same place, so x + ~x is all ones, which is −1. Then ~x = −1 − x, and adding 1 gives −x. Here it is for 44:

Negating 44
0−12806413201618140201
44
1−12816403211608041211
Flip every bit: −128 + 64 + 16 + 2 + 1 = −45

4 The six bit operators

The bit operators work on each column of bits on its own. Four of them compare or flip bits. With a = 12 and b = 10:

ExpressionA bit is 1 whenBitsValue
a0000 110012
b0000 101010
a & b (AND)both bits are 10000 10008
a | b (OR)either bit is 10000 111014
a ^ b (XOR)the two bits differ0000 01106
~a (NOT)a's bit is 01111 0011−13

~a is −13 because of the rule from the last section: ~x = −x − 1. In your language, NOT is written ~.

XOR has four facts that whole problems rest on:

  • x ^ 0 = x. XOR with 0 changes nothing.
  • x ^ x = 0. A bit never differs from itself.
  • The order does not matter. In 12 ^ 10 ^ 12, the two 12s cancel and leave 10.
  • x ^ y marks the differences. 12 ^ 10 is 0110, so 12 and 10 differ in bits 1 and 2.

The last two operators slide the whole row:

  • x << k moves every bit k places left, and 0s come in on the right. It multiplies by 2ᵏ: 44 << 1 is 88.
  • x >> k moves every bit k places right, and the lowest k bits fall off. It divides by 2ᵏ and rounds down: 44 >> 3 is 5.
Shifting 44 by one place
0−12806413201618140201
44
0−12816403211618040201
44 << 1 = 88: each 1 moves up a place, and its worth doubles

In 44 >> 3, the 1 in the 4s box falls off the end. That lost 4 is the rounding: 44 ÷ 8 is 5.5, and the shift gives 5.

Each operator works on all the bits at once, so each one is a single step, O(1).

5 Check, set, clear and toggle one bit

Many problems need one bit of a number. The tool is a mask, a number with 1s only where we want to act. 1 << i has only bit i on. For i = 3, it is 00001000.

AND with 1, OR with 0 and XOR with 0 all keep a bit as it is. So each operation below changes bit i and leaves the rest alone:

  • Check: (n >> i) & 1. The shift brings bit i down to bit 0, and & 1 keeps only that bit.
  • Set: n | (1 << i). OR with 1 makes the bit 1.
  • Clear: n & ~(1 << i). The flipped mask has a 0 only at bit i, and AND with 0 makes the bit 0.
  • Toggle: n ^ (1 << i). XOR with 1 flips the bit.

Clearing takes two steps. Here it is on 44, with i = 3:

Clearing bit 3 of 44
0−12806413201618140201bit 3
44
0−12806403201618040201
The mask 1 << 3 = 8

In 44, bit 3 is on and bit 4 is off. All four operations on each:

BitCheckSetClearToggle
i = 3, on1443636
i = 4, off0604460

Setting a bit that is on, or clearing one that is off, changes nothing. With i = 0, the check reads the lowest bit: n & 1 is 1 exactly when n is odd.

For 44, every tab gives the table's results, with true or false for the check. Each operation is O(1).

6 Two tricks with the lowest 1 bit

Subtracting 1 changes a number in a fixed pattern. In base 10, 300 − 1 = 299. The lowest digit that is not 0 goes down by one, and the 0s below it become 9s. Binary works the same way, with 1 in place of 9. In n − 1, the lowest 1 of n becomes 0, the 0s below it become 1s, and the bits above it stay.

So n & (n - 1) clears the lowest 1. Above it, n and n − 1 match, so AND keeps those bits. From it down, they never both have a 1, so AND gives 0s.

44 & 43 drops the lowest 1
0−12806413201618140201lowest 1
44
0−12806413201618041211
43 = 44 − 1: the lowest 1 turns to 0, and the 0s below it turn to 1

Each use removes one 1 bit. So a loop of n = n & (n - 1) until n is 0 runs once per 1 bit, not once per bit. A power of two has a single 1 bit, so one use leaves 0: 32 & 31 = 0.

The second trick, n & -n, keeps only the lowest 1. It rests on −n = ~n + 1. The flip turns the lowest 1 of n into a 0 and the 0s below it into 1s. Adding 1 carries through those 1s and stops at that 0. So −n matches n from the lowest 1 down, and is the flip of n above it.

44 & −44 keeps the lowest 1
0−12806413201618140201lowest 1
44
1−12816403211608140201
−44: 44 flipped above the lowest 1 only

Above the lowest 1, each bit meets its own flip, so AND gives 0 there. Only the lowest 1 is left.

For 44, every tab gives 40 and 4. For 32, it gives 0 and 32. Both tricks are O(1).

7 Mistakes and traps

  • Comparing a masked bit with 1. (n & (1 << i)) == 1 fails for every i except 0. For n = 44 and i = 3, n & 8 is 8, so a bit that is on looks off. Compare with 0 instead, or shift first.
  • Missing brackets. In several languages, == binds tighter than &. Then x & 1 == 0 means x & (1 == 0). And 1 << i + 1 means 1 << (i + 1) in most languages. Put brackets round every bit expression.
  • Shifting 1 past the width. In a 32-bit int, 1 << 31 lands on the sign bit and gives −2³¹. 1 << 32 is not 2³², and most languages give a wrong value without any error. A mask for a 64-bit number needs a 64-bit 1.
  • Shifting a negative number right. >> copies the sign bit into the top, so -8 >> 1 is −4. But -1 >> 1 is −1 again, so a loop that shifts n right until it is 0 never ends on a negative n. For 0s at the top, the number must be treated as unsigned.

C++

x & 1 == 0 compiles. It means x & 0, so it is always false. A compiler warning is the only sign.

Use 1LL << i for a long long. 1 << 32 on an int is undefined, and it often gives 1.

Shift an unsigned for 0s. >> on a negative int copies the sign bit. (unsigned)n >> 1 fills the top with 0, so −8 becomes 2147483644.

x & 1 == 0 is a Compile Error, because 1 == 0 is a boolean.

Use 1L << i for a long. Java takes an int shift count modulo 32, so 1 << 32 is 1.

>>> fills with 0s. -8 >> 1 is −4, and -8 >>> 1 is 2147483644.

x & 1 == 0 works, because & binds tighter than == in Python. Brackets are still a good habit.

Integers have no width. 1 << 40 is fine, and 1 << 31 is positive.

There is no >>>, and ~ has no width. −8 >> 1 is −4, and ~44 is −45, not 211. To work on 32 bits, take n & 0xFFFFFFFF first. To flip only 8 bits, use 44 ^ 0xFF.

x & 1 == 0 is always 0. It means x & false, and false acts as 0. No error appears.

Bit operators use 32 bits. 1 << 31 is −2147483648, and 1 << 32 is 1. Any bit operator first cuts a number to its lowest 32 bits, so it breaks values past about 2.1 × 10⁹. BigInt handles more: 1n << 40n.

>>> fills with 0s. -8 >> 1 is −4, and -8 >>> 1 is 2147483644.

x&1 == 0 works, because & binds tighter than ==. But << binds as tightly as *, so 1 << i + 1 is (1 << i) + 1. Most languages read it the other way.

int is 64 bits, so 1 << 40 fits. An int32 shifted left by 32 or more becomes 0.

Shift an unsigned type for 0s. >> on a negative int copies the sign bit. uint32(n) >> 1 fills the top with 0s.

x & 1 == 0 works, because & binds tighter than ==.

Use 1i64 << i for an i64. Shifting an i32 by 32 or more is an overflow.

Shift a u32 for 0s. >> on an i32 copies the sign bit. On a u32 it fills with 0s, as in (n as u32) >> 1.

x & 1 == 0 is a Compile Error, because 1 == 0 is a bool.

Use 1L << i for a long. C# takes an int shift count modulo 32, so 1 << 32 is 1.

>>> fills with 0s. -8 >> 1 is −4, and -8 >>> 1 is 2147483644.

8 When to use bit operators

A problem needs these tools when it asks about the bits of a number. Each kind of question has its own tool:

  • One bit. Check, set, clear or toggle it with the mask 1 << i.
  • Odd or even, half or double. Use n & 1, n >> 1 and n << 1.
  • The 1 bits, one at a time. n & (n - 1) drops the lowest, and n & -n finds it.
  • Pairs that cancel. When every value appears twice except one, XOR cancels the pairs.
  • Where two numbers differ. x ^ y has a 1 in each such place.

The next lesson, on bitmasks, uses the bits of one integer as a set: bit i is on when item i is in the set.

Before trusting a bit trick, write the numbers in 8 bits, one under the other, and work each column by hand.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.