A4 · Lesson 4 · Bits, bytes and binary data
Taking integers apart the way hardware builds them
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?
- Shifting left by 4 bits multiplies by , 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.
Name it
Binary and hex
An integer is stored as bits, and Python lets you write and show it in any base:
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 & 0b1010is0b1000.a | b, OR: 1 where either bit is 1.0b1100 | 0b1010is0b1110.a ^ b, XOR: 1 where the bits differ.0b1100 ^ 0b1010is0b0110.~a, NOT: flips every bit. Python's integers have no fixed width, so~ais .a << nshifts left places, multiplying by ;a >> nshifts right, dividing by and dropping the remainder.
Masks: reading and writing fields
A mask is a number with 1s where you care. Bit alone is 1 << n, and ones in a row are (1 << w) - 1.
(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).
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 -bit pattern whose top bit is set stands for the pattern minus . For 16 bits, 0xFFFF is −1 and 0x8000 is −32768:
v = raw - (1 << 16) if raw >= (1 << 15) else raw
int.from_bytes(b, "big", signed=True) # the same thing from bytesWorked 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?
Show the solution
- 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.
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
- Scale the first reading. 0x196 is 406 sixteenths of a degree:
- Take the top 12 bits of 0xE7, 0x00. The 16-bit value is 0xE700 and the top 12 bits are 0xE70 = 3696.
- Undo the two's complement. 3696 is at least 2048, so the top bit is set:
- 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.
Worked 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.
Show the solution
- Read the fields, then set and clear the bits. Shift and mask for each field; OR in bit 15 and AND out bit 7.
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
- Write the register in binary. Four bits per hex digit make each field visible:
- 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.
- 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.
Worked 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.
Show the solution
- XOR the bytes together. Keep a running XOR, starting from 0.
c = 0
for b in [0x02, 0x10, 0xA5, 0x3C]:
c ^= b
print(hex(c)) # 0x8b
- Follow the running XOR.
- 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.
- Flip one bit. If the third byte arrives as 0xA4, the data's XOR becomes 0x8A, which doesn't match 0x8B.
- 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
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 = 0xBEEF, pos = 0 and width = 4.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
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 = 0xBEEF, pos = 0 and v = 9.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
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 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
What is 0x66 in decimal?
Check
What does ~5 give in Python?
Check
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 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
A 16-bit signed register reads 32767 when you treat it as unsigned. What signed value does it hold?
Check
What is list((0x1234).to_bytes(2, "little"))?
Explain why
Why do datasheets describe registers in hex rather than decimal?
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
Keep practicing
8 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.