|q⟩ Bad Qubits

intermediate · Programming · Multi-Qubit Registers & State Simulation

Computational Basis Encoding

Classical computers store numbers as strings of bits — 0s and 1s — and quantum computers do the same at the register level. Understanding how integers map to multi-qubit states is essential before you can write any algorithm that processes numerical data.

Binary representation

Every non-negative integer nn can be written uniquely in base 2:

n=bk12k1+bk22k2++b12+b0,n = b_{k-1}\,2^{k-1} + b_{k-2}\,2^{k-2} + \cdots + b_1\,2 + b_0,

where each bi{0,1}b_i \in \{0,1\}. The kk-bit string bk1b1b0b_{k-1}\ldots b_1 b_0 is the binary representation of nn. For example,

5=14+02+11=(101)2.5 = 1 \cdot 4 + 0 \cdot 2 + 1 \cdot 1 = (101)_2.

Computational basis states

An nn-qubit register has a computational basis of 2n2^n states, 0,1,,2n1|0\rangle, |1\rangle, \ldots, |2^n - 1\rangle, one for every non-negative integer that fits in nn bits. The state j|j\rangle is the tensor product of the individual qubit states that spell out the binary digits of jj. With qubit 0 as the most significant bit:

j=bn1bn2b0,|j\rangle = |b_{n-1}\rangle \otimes |b_{n-2}\rangle \otimes \cdots \otimes |b_0\rangle,

where j=i=0n1bi2n1ij = \sum_{i=0}^{n-1} b_i\,2^{n-1-i}.

For a 3-qubit register the eight basis states are:

| Integer | Binary | State | |---------|--------|-------| | 0 | 000 | 000|000\rangle | | 1 | 001 | 001|001\rangle | | 2 | 010 | 010|010\rangle | | 3 | 011 | 011|011\rangle | | 4 | 100 | 100|100\rangle | | 5 | 101 | 101|101\rangle | | 6 | 110 | 110|110\rangle | | 7 | 111 | 111|111\rangle |

Encoding with X gates

Every qubit starts in 0|0\rangle. To encode an integer jj, apply an XX gate to each qubit whose corresponding bit in jj is 1. The XX gate flips 01|0\rangle \to |1\rangle (and 10|1\rangle \to |0\rangle), so selectively applying it writes 1s in the right positions.

To encode 5=(101)25 = (101)_2 in a 3-qubit register (qubit 0 = MSB):

The resulting state is 101=5|101\rangle = |5\rangle.

General recipe

Given an integer jj and a register of nn qubits (qubit 0 = MSB, qubit n1n-1 = LSB):

  1. Write jj in binary: bn1b1b0b_{n-1}\ldots b_1 b_0.
  2. For each position ii where bi=1b_i = 1, call c.x(i).

The register is then in the pure state j|j\rangle with amplitude 1.

Try it

Encode the integer 5 into a 3-qubit register. The grader checks the full statevector, so the amplitude of 101|101\rangle must be 1 and all others must be 0.

Run your code to see the quantum state.

After running, look at the statevector panel: the only non-zero amplitude should appear at index 5 (the binary string 101), confirming the register holds 5|5\rangle.

Sign in on the full site to ask questions and join the discussion.