Skip to lesson
0/174 complete
LEARN THE CONCEPTFree forever

Binary representation

Topic 1 of 6 · Bit manipulation

What is a bit?

A bit is a binary digit: either 0 or 1. Binary represents numbers using powers of two rather than powers of ten. Bit manipulation reads or changes these individual digits using operations such as AND, OR, XOR, and shifts. A mask is a bit pattern used to select particular positions.

Example: Binary 101 means 1×4 + 0×2 + 1×1 = 5. The rightmost position represents 1, the next represents 2, and the next represents 4.

INTERACTIVE WALKTHROUGHPredict · step · explain
SHARED CHAPTER LAB · BITS

13 is 1101.

bit 31
bit 21
bit 10
bit 01
1 / 4

Step 1 of 4 · set bits=3

Interview reasoningWorked exampleTry it yourself
Self-paced learning
Helpful before this chapter

If these ideas are new, begin with:

Understand the idea

Binary position i contributes 2^i when set. The least significant bit has index zero. Leading zeros do not change a nonnegative value; width matters for signed and complement operations.

Work through an example

13=8+4+1=1101₂. Positions 3,2,0 are set. A four-bit unsigned range is 0..15; signed two's-complement width four is -8..7.

Time and space complexity

Fixed machine-word operations are O(1); arbitrary-width work depends on bit length.

Why it works

An integer equals the sum of its set-bit place values.

Common mistakes

  • Do not confuse displayed leftmost position with bit zero.
  • Signed and unsigned ranges differ.

Chapter lab · Python implementation

Bit operations treat an integer as binary positions. Our lab clears the lowest set bit repeatedly and enumerates subsets with masks. Examples use nonnegative integers unless an explicit width is supplied. Python integers are unbounded, so signed NOT and shifting differ from unsigned fixed-width machine examples.

This shared lab connects the chapter's topics. Follow the current lesson's worked example first, then trace the complete implementation. Additional algorithms described in topic exercises are variations you can implement independently.

def count_bits(value):
    if value<0: raise ValueError('nonnegative value required')
    count=0
    while value:
        value &= value-1
        count+=1
    return count

def subsets_mask(values):
    output=[]
    for mask in range(1<<len(values)):
        output.append([x for i,x in enumerate(values) if mask & (1<<i)])
    return output

def complement(value,width):
    if width<1 or not 0<=value<(1<<width):
        raise ValueError('value must fit width')
    return (~value)&((1<<width)-1)

Run and test the lab

Copy the implementation and these assertions into a Python 3 file and run it. An assertion failure means the actual result differs from the expectation. Add the current topic's exercise and boundary tests to deepen your understanding.

assert count_bits(13)==3 and count_bits(0)==0
assert complement(5,4)==10
assert subsets_mask(['a','b'])==[[],['a'],['b'],['a','b']]
assert all(count_bits(x)==bin(x).count('1') for x in range(256))
CHECK YOUR UNDERSTANDING

What value is binary 1010?

Course outline
Software Engineer
DSA
THE SOFTWARE ENGINEERING PATH

Data Structures
& Algorithms

Build intuition. Develop a pattern.
Make it your own.

Free course30 chapters
Your progress0%

0 of 174 published lessons complete