12-bit Sensor Log and Two's Complement
An embedded data logger records 1,000 sensor readings. Each reading is a 12-bit signed integer in two's complement form. The logger stores each reading in a 16-bit word: the low 12 bits hold the reading and the top 4 bits are set to zero. Memory is byte-addressable, and the first reading is stored at base address 0x2000. The logger's firmware has no separate sign field; it reconstructs the signed value by interpreting the low 12 bits and then sign-extending to 16 bits when needed. A junior engineer reads the raw word 0x0ABC from the 100th reading and mistakenly treats it as a positive 16-bit integer. The team must verify the value range, the storage layout, and the correct interpretation before the next firmware release.
1. What is the range of values representable by a 12-bit two's complement integer? Express -5 in 12-bit two's complement and as the stored 16-bit word.
Read the worked answer
For n bits, the two's complement range is -2^(n-1) to 2^(n-1) - 1. For n=12: -2048 to 2047.
To encode -5 in 12 bits: 2^12 - 5 = 4096 - 5 = 4091. 4091 = 0xFFB (0xF00 = 3840, remainder 251 = 0xFB). As a 16-bit word with the top four bits zero, it is 0x0FFB. Check: bit 11 of 0xFFB is set (0x800), so the 12-bit value is negative; magnitude = 0x1000 - 0xFFB = 5.
2. How many bytes does the 1,000-reading log occupy? At what address is the 100th reading stored?
Read the worked answer
Each reading occupies one 16-bit word = 2 bytes, because the logger stores each 12-bit value in a 16-bit word. 1,000 * 2 = 2,000 bytes = 0x7D0.
The first reading is at 0x2000. The 100th reading is index 99 in zero-based indexing, so offset = 99 * 2 = 198 = 0xC6. Address = 0x2000 + 0x00C6 = 0x20C6. The log ends at 0x2000 + 0x7D0 = 0x27D0 exclusive, so the last byte is 0x27CF.
3. The junior engineer reads raw word 0x0ABC from the 100th reading. What signed value does it represent under the logger's scheme? Explain the sign-extension step.
Read the worked answer
Take the low 12 bits: 0xABC. Since bit 11 is set (0x800), the 12-bit value is negative. Value = 0xABC - 0x1000 = 2748 - 4096 = -1348. Sign extension to 16 bits copies bit 11 into bits 12-15, producing 0xFABC, which as a 16-bit two's complement integer is -1348 (0x10000 - 0xFABC = 0x544 = 1348). The junior engineer's positive reading of 0x0ABC = 2748 is wrong because it ignores the 12-bit sign bit. Notice that the stored top four bits are zero, so the raw 16-bit word 0x0ABC is positive; the sign must be recovered from bit 11 before extension.