I2C addressing (7-bit and 10-bit) in Embedded C - Time & Space Complexity
When working with I2C communication, it's important to understand how addressing affects the time it takes to send data.
We want to see how the number of bits in the address changes the work the microcontroller does.
Analyze the time complexity of the following code snippet.
// Send I2C address (7-bit or 10-bit)
void i2c_send_address(uint16_t address, bool is_10bit) {
if (is_10bit) {
// Send 10-bit prefix + high bits (11110 A9 A8 0)
i2c_write(((address >> 7) & 0x06) | 0xF0);
// Send last 8 bits
i2c_write(address & 0xFF);
} else {
// Send 7-bit address
i2c_write(address << 1);
}
}
This code sends either a 7-bit or 10-bit I2C address by writing bytes to the bus.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calls to
i2c_write()to send address bytes. - How many times: For 7-bit address, 1 call; for 10-bit address, 2 calls.
As the address size grows from 7 to 10 bits, the number of write operations increases slightly.
| Address Size (bits) | Write Calls |
|---|---|
| 7 | 1 |
| 10 | 2 |
| 14 (hypothetical) | 3 |
Pattern observation: Each additional 7 bits roughly adds one more write operation.
Time Complexity: O(1)
This means the time to send the address does not grow with input size in a way that depends on variable data; it stays constant.
[X] Wrong: "Sending a 10-bit address takes twice as long as a 7-bit address because it has more bits."
[OK] Correct: The code sends a fixed small number of bytes regardless of address size, so the time difference is small and constant, not proportional to the number of bits.
Understanding how fixed-size operations affect timing helps you explain device communication clearly and confidently.
"What if the I2C address size increased to 15 bits? How would the time complexity change?"