---
title: Bits, bytes and binary data
heading: Taking integers apart the way hardware builds them
eyebrow: A4 · Lesson 4 · Bits, bytes and binary data
xp: 40
---

::: hook
A temperature sensor on an I²C bus doesn't send "25.4 °C". It sends two bytes, 0x19 and 0x60, and its datasheet says the top 12 bits are the temperature in sixteenths of a degree. A status register packs a dozen flags into one number, and a radio packet ends with a checksum computed byte by byte. Code that talks to hardware has to take integers apart bit by bit and put them back together, and Python's integer operators do exactly that.
:::

::: predict
## What is `0x17 << 4`?

- [ ] 92, which is 0x17 times 4
- [x] 368, which is 0x170
- [ ] 0x1704
- [ ] 1.4375

::: reveal
368. Shifting left by 4 bits multiplies by $2^4 = 16$, and 0x17 is 23, so the result is 368. In hex that's 0x170: one hex digit is exactly 4 bits, so a 4-bit shift moves every hex digit one place left. Shifting right by 4 would divide by 16 and drop the remainder.
:::
:::

::: nameit
## Binary and hex

An integer is stored as bits, and Python lets you write and show it in any base:

```python
0b1011          # 11, written in binary
0x1F            # 31, written in hex
bin(11)         # '0b1011'
hex(31)         # '0x1f'
f"{11:08b}"     # '00001011', 8 binary digits
f"{31:04X}"     # '001F', 4 hex digits, capitals
int("1F", 16)   # 31, from text in base 16
```

One hex digit is exactly 4 bits, so a byte (8 bits, 0 to 255) is two hex digits and a 16-bit register is four. That's why datasheets use hex: you can read the bits straight off it. 0xA is 1010, 0x5 is 0101, 0xF is 1111.

## Bitwise operators

These work on each bit position separately:

- `a & b`, AND: 1 where both bits are 1. `0b1100 & 0b1010` is `0b1000`.
- `a | b`, OR: 1 where either bit is 1. `0b1100 | 0b1010` is `0b1110`.
- `a ^ b`, XOR: 1 where the bits differ. `0b1100 ^ 0b1010` is `0b0110`.
- `~a`, NOT: flips every bit. Python's integers have no fixed width, so `~a` is $-a - 1$.
- `a << n` shifts left $n$ places, multiplying by $2^n$; `a >> n` shifts right, dividing by $2^n$ and dropping the remainder.

## Masks: reading and writing fields

A **mask** is a number with 1s where you care. Bit $n$ alone is `1 << n`, and $w$ ones in a row are `(1 << w) - 1`.

```python
(x >> n) & 1                    # read bit n
(x >> p) & ((1 << w) - 1)       # read the w-bit field starting at bit p
x | (1 << n)                    # set bit n
x & ~(1 << n)                   # clear bit n
x ^ (1 << n)                    # toggle bit n
```

## Bytes and byte order

`bytes([0x19, 0x60])` holds two raw bytes. Turning them into one number needs a **byte order**: big-endian puts the most significant byte first (network protocols, most sensors), little-endian puts it last (x86 and ARM memory).

```python
int.from_bytes(bytes([0x19, 0x60]), "big")      # 0x1960 = 6496
int.from_bytes(bytes([0x19, 0x60]), "little")   # 0x6019 = 24601
(6496).to_bytes(2, "big")                       # b'\x19`', the bytes 0x19 0x60
```

## Signed values: two's complement

Hardware stores negative numbers in **two's complement**: an $n$-bit pattern whose top bit is set stands for the pattern minus $2^n$. For 16 bits, 0xFFFF is −1 and 0x8000 is −32768:

```python
v = raw - (1 << 16) if raw >= (1 << 15) else raw
int.from_bytes(b, "big", signed=True)          # the same thing from bytes
```
:::

::: example
## A TMP102 temperature sensor returns the bytes 0x19 then 0x60. Its temperature is the top 12 bits of the big-endian 16-bit value, in two's complement, in steps of 0.0625 °C. What temperature is it? And for 0xE7 then 0x00?

::: solution
1. **Join the bytes and drop the low four bits.** The shift drops the four unused low bits, and a set top bit then means a negative value.

```python
raw = int.from_bytes(bytes([0x19, 0x60]), "big")   # 0x1960
t12 = raw >> 4                                      # 0x196 = 406
if t12 >= 2048:                                     # top bit of 12 set: negative
    t12 -= 4096
print(t12 * 0.0625)                                 # 25.375
```

2. **Scale the first reading.** 0x196 is 406 sixteenths of a degree:
   $$\begin{aligned} T &= 406 \times 0.0625 \\ &= 25.375\ \text{°C} \end{aligned}$$
3. **Take the top 12 bits of 0xE7, 0x00.** The 16-bit value is 0xE700 and the top 12 bits are 0xE70 = 3696.
4. **Undo the two's complement.** 3696 is at least 2048, so the top bit is set:
   $$\begin{aligned} 3696 - 4096 &= -400 \\ -400 \times 0.0625 &= -25.0\ \text{°C} \end{aligned}$$
5. **Check against the datasheet.** It lists exactly 0xE70 for −25 °C, which is a good way to test a decoder: feed it the table's own examples.

**Answer:** 0x19, 0x60 is 25.375 °C, and 0xE7, 0x00 is −25.0 °C.
:::
:::

::: example
## A converter's status register reads 0x13A6. Bits 0 to 3 are the channel, bit 7 is "ready" and bits 8 to 11 are the gain code. Read all three, then set bit 15 (start) and clear bit 7.

::: solution
1. **Read the fields, then set and clear the bits.** Shift and mask for each field; OR in bit 15 and AND out bit 7.

```python
x = 0x13A6                      # 0001 0011 1010 0110
channel = x & 0xF               # 6
ready = (x >> 7) & 1            # 1
gain = (x >> 8) & 0xF           # 3
x = (x | (1 << 15)) & ~(1 << 7)
print(hex(x))                   # 0x9326
```

2. **Write the register in binary.** Four bits per hex digit make each field visible:
   $$\text{0x13A6} = 0001\ 0011\ 1010\ 0110$$
3. **Read off the fields.** The low digit 0x6 is the channel, the top bit of 0xA (1010) is the ready flag, and the 0x3 in the third place is the gain.
4. **Set bit 15 and clear bit 7.** Setting bit 15 turns the leading 0x1 into 0x9, and clearing bit 7 turns 0xA6 into 0x26.

**Answer:** the channel is 6, ready is 1 and the gain code is 3; after the writes the register holds 0x9326.
:::
:::

::: example
## A link protects each packet with an 8-bit XOR checksum: the XOR of every byte. Find the checksum of 0x02, 0x10, 0xA5, 0x3C, and show that the receiver catches a single flipped bit.

::: solution
1. **XOR the bytes together.** Keep a running XOR, starting from 0.

```python
c = 0
for b in [0x02, 0x10, 0xA5, 0x3C]:
    c ^= b
print(hex(c))                   # 0x8b
```

2. **Follow the running XOR.**
   $$\begin{aligned} \text{0x02} \oplus \text{0x10} &= \text{0x12} \\ \text{0x12} \oplus \text{0xA5} &= \text{0xB7} \\ \text{0xB7} \oplus \text{0x3C} &= \text{0x8B} \end{aligned}$$
3. **Check at the receiver.** The receiver XORs every byte it gets, checksum included; a clean packet gives 0, because each bit has been XORed with itself.
4. **Flip one bit.** If the third byte arrives as 0xA4, the data's XOR becomes 0x8A, which doesn't match 0x8B.
5. **Know the limit.** A single flipped bit always changes the XOR, though two flips in the same bit position cancel, which is why serious links use CRCs.

**Answer:** the checksum is 0x8B, and a single flipped bit always changes the XOR (to 0x8A when the third byte arrives as 0xA4), so the receiver catches it.
:::
:::

::: check
kind: python
given: reg = 0x13A6 | 0xBEEF | 0x7F01 | 0x0F5C; pos = 0 | 4 | 6 | 9; width = 2 | 3 | 4

## Write `field(x, pos, width)` returning the `width`-bit field of `x` that starts at bit `pos`. Then set `f = field(reg, pos, width)` with `reg` = 0x{reg:hex4}, `pos` = {pos} and `width` = {width}.

```python starter
def field(x, pos, width):
    return x >> pos

f = field(reg, pos, width)
print(f)
```

```python solution
def field(x, pos, width):
    return (x >> pos) & ((1 << width) - 1)

f = field(reg, pos, width)
print(f)
```

```python tests
assert f == (reg >> pos) & ((1 << width) - 1), f"The field is {(reg >> pos) & ((1 << width) - 1)}: shift right by pos, then mask with (1 << width) - 1."
assert field(0b110110, 1, 3) == 0b011, "field(0b110110, 1, 3) should be 0b011."
```

::: right
Right. The shift brings the field down to bit 0 and the mask keeps exactly `width` bits of it.
:::
:::

::: check
kind: python
given: reg = 0x13A6 | 0xBEEF | 0x0000 | 0xFFFF; pos = 0 | 4 | 8; v = 0 | 5 | 9 | 15

## Write `set_field(x, pos, width, value)` returning `x` with its `width`-bit field at `pos` replaced by `value`, leaving every other bit alone. Then set `y = set_field(reg, pos, 4, v)` with `reg` = 0x{reg:hex4}, `pos` = {pos} and `v` = {v}.

```python starter
def set_field(x, pos, width, value):
    return x | (value << pos)

y = set_field(reg, pos, 4, v)
print(hex(y))
```

```python solution
def set_field(x, pos, width, value):
    mask = ((1 << width) - 1) << pos
    return (x & ~mask) | ((value << pos) & mask)

y = set_field(reg, pos, 4, v)
print(hex(y))
```

```python tests
m = 0xF << pos
want = (reg & ~m) | (v << pos)
assert y == want, f"y should be {hex(want)}: clear the field with & ~mask first, then OR in the new value."
assert set_field(0xFF, 0, 4, 0x3) == 0xF3, "Setting the low nibble of 0xFF to 3 should give 0xF3: the old 1s must be cleared first."
```

::: right
Right. OR alone can only turn bits on, so the field has to be cleared first with `& ~mask`. Masking the value too stops a too-large value from spilling into the neighboring field.
:::
:::

::: check
kind: python
given: k = 0..4 int

## Write `tmp102(b1, b2)` that turns a TMP102's two bytes (most significant first) into °C: the top 12 bits of the 16-bit value, two's complement, times 0.0625. Then set `t` for the byte pair the starter picks.

```python starter
pairs = [(0x19, 0x60), (0xE7, 0x00), (0x7F, 0xF0), (0xFF, 0xC0), (0x00, 0x40)]
b1, b2 = pairs[k]

def tmp102(b1, b2):
    return ((b1 << 8) | b2) * 0.0625

t = tmp102(b1, b2)
print(t)
```

```python solution
pairs = [(0x19, 0x60), (0xE7, 0x00), (0x7F, 0xF0), (0xFF, 0xC0), (0x00, 0x40)]
b1, b2 = pairs[k]

def tmp102(b1, b2):
    t12 = ((b1 << 8) | b2) >> 4
    if t12 >= 2048:
        t12 -= 4096
    return t12 * 0.0625

t = tmp102(b1, b2)
print(t)
```

```python tests
want = [25.375, -25.0, 127.9375, -0.25, 0.25][k]
assert abs(t - want) < 1e-12, f"For these bytes the temperature is {want} °C. Shift right by 4, then subtract 4096 if the 12-bit value is 2048 or more."
assert tmp102(0x00, 0x00) == 0.0, "Zero bytes should give 0 °C."
```

::: right
Right. The low four bits are unused, so shift them away; then the 12-bit field's top bit decides the sign. 0xFF 0xC0 is the classic test: it's −0.25 °C, not 4095.75.
:::
:::

::: check
given: n = 16..255 int
answer: n
tolerance: 0.1

## What is `0x{n:hex2}` in decimal?

::: right
Right. The left hex digit counts sixteens and the right one counts ones: {answer}.
:::

::: misses
- [any] Not yet. Multiply the left digit by 16 and add the right one, with A to F standing for 10 to 15.
:::
:::

::: check
kind: choice

## What does `~5` give in Python?

- [x] `-6`
- [ ] `250`
- [ ] `2`
- [ ] `-5`

::: right
Right. Python's integers have no fixed width, so flipping every bit of 5 gives $-5 - 1 = -6$ in two's complement. To flip just the low 8 bits, mask the result: `~5 & 0xFF` is 250.
:::

::: misses
- [2] That's `~5 & 0xFF`, the 8-bit answer. Without a mask Python has no width to stop at, and `~5` is −6.
- [3] That's 5 shifted right. `~` flips every bit.
- [4] Flipping every bit of $x$ gives $-x - 1$ in two's complement.
:::
:::

::: check
kind: python
given: k = 0..3 int

## Write `checksum(bs)` returning the XOR of all the bytes in a list, and `valid(packet)` returning `True` when the last byte of `packet` equals the checksum of the bytes before it. Then set `c = checksum(data)` and `ok = valid(packet)` for the packet the starter picks.

```python starter
packets = [[0x02, 0x10, 0xA5, 0x3C, 0x8B], [0x01, 0x02, 0x03, 0x00], [0xFF, 0x0F, 0xF0, 0x01], [0x55, 0xAA, 0x55, 0xAA, 0x00]]
packet = packets[k]
data = packet[:-1]

def checksum(bs):
    return sum(bs) % 256

def valid(packet):
    return True

c = checksum(data)
ok = valid(packet)
print(hex(c), ok)
```

```python solution
packets = [[0x02, 0x10, 0xA5, 0x3C, 0x8B], [0x01, 0x02, 0x03, 0x00], [0xFF, 0x0F, 0xF0, 0x01], [0x55, 0xAA, 0x55, 0xAA, 0x00]]
packet = packets[k]
data = packet[:-1]

def checksum(bs):
    c = 0
    for b in bs:
        c ^= b
    return c

def valid(packet):
    return checksum(packet[:-1]) == packet[-1]

c = checksum(data)
ok = valid(packet)
print(hex(c), ok)
```

```python tests
want_c = [0x8B, 0x00, 0x00, 0x00][k]
want_ok = [True, True, False, True][k]
assert c == want_c, f"The XOR of these bytes is {hex(want_c)}."
assert ok == want_ok, f"This packet is {'valid' if want_ok else 'corrupt'}."
assert valid([0x12, 0x34, 0x12 ^ 0x34]) and not valid([0x12, 0x34, 0x00]), "valid compares the last byte with the XOR of the others."
```

::: right
Right. XOR is its own inverse, so 1 ^ 2 ^ 3 is 0 and so is 0x55 ^ 0xAA ^ 0x55 ^ 0xAA: an XOR checksum can be zero for data that isn't.
:::
:::

::: check
given: r = 1000 | 32767 | 40000 | 50000 | 65535
answer: r - 65536*step(r - 32767.5)
tolerance: 0.1

## A 16-bit signed register reads {r} when you treat it as unsigned. What signed value does it hold?

::: right
Right. Patterns from 32768 up have the top bit set and stand for the pattern minus 65536; below that they're the number itself: {answer}.
:::

::: misses
- [r - 32768] Two's complement subtracts $2^{16}$ = 65536, the whole range.
- [any] Not yet. If the pattern is 32768 or more, subtract 65536; otherwise it stands for itself.
:::
:::

::: check
kind: choice

## What is `list((0x1234).to_bytes(2, "little"))`?

- [x] `[52, 18]`, the bytes 0x34 then 0x12
- [ ] `[18, 52]`, the bytes 0x12 then 0x34
- [ ] `[4660]`
- [ ] `[1, 2, 3, 4]`

::: right
Right. Little-endian puts the least significant byte first: 0x34 (52), then 0x12 (18). Reading a little-endian device as big-endian swaps them, a classic bug that turns 0x1234 into 0x3412.
:::

::: misses
- [2] That's big-endian order, most significant byte first.
- [3] `to_bytes(2, ...)` splits the number into two bytes.
- [4] Each byte holds two hex digits, so 0x1234 is two bytes.
:::
:::

::: explain
## Why do datasheets describe registers in hex rather than decimal?

::: model
Each hex digit stands for exactly four bits, so the bit pattern can be read straight off a hex number: 0xA6 is 1010 0110, and a field that starts on a 4-bit boundary is a single digit. A decimal number mixes all the bits together: 166 doesn't tell you which flags are set without converting it. Since registers are collections of bits and fields, hex shows their structure and decimal hides it.
:::
:::

::: practice

::: check
kind: python
given: x = 0x5A | 0xFF | 0x80 | 0x0137 | 0xBEEF

## Set `ones` to how many bits of `x` = 0x{x:hex4} are 1, using a loop with `& 1` and `>>`.

```python starter
ones = 0
print(ones)
```

```python solution
ones = 0
y = x
while y:
    ones += y & 1
    y >>= 1
print(ones)
```

```python tests
assert ones == bin(x).count("1"), f"0x{x:04X} has {bin(x).count('1')} bits set."
```
:::

::: check
kind: python
given: b = 0..255 int

## Set `s` to the byte `b` = {b} written as exactly 8 binary digits (with leading zeros) and `h` as exactly two capital hex digits, both as strings.

```python starter
s = bin(b)
h = hex(b)
print(s, h)
```

```python solution
s = f"{b:08b}"
h = f"{b:02X}"
print(s, h)
```

```python tests
assert s == format(b, "08b"), f"s should be {format(b, '08b')!r}: use f'{{b:08b}}'."
assert h == format(b, "02X"), f"h should be {format(b, '02X')!r}: use f'{{b:02X}}'."
```
:::
:::
