How do you write Python code to unpack 12-bit data?
General knowledgeAsked by Anonymous22 Oct 2026, 11:22 PM ISTUpdated
In one line
To unpack 12-bit data in Python, you split a stream of bytes into separate 12-bit numbers.
The rule
Unpacking 12-bit data means extracting each 12-bit value from a packed byte sequence.
There is no single formula, but the idea is: read every 3 bytes (24 bits), and split them into two 12-bit numbers.
Let's understand it simply
Imagine you have a box of ladoos, but each ladoo is cut into 12 pieces. The shopkeeper packs them in a way that every 3 pieces (bytes) actually hold 2 full ladoos (12-bit numbers). To eat a full ladoo, you need to carefully take out the right 12 pieces from the packed box.
In computers, data is often packed tightly to save space. But most computers use 8 bits (1 byte) as the basic unit. So, 12-bit data doesn't fit neatly into bytes. We have to do some cutting and joining to get each 12-bit number out.
How it works
Read the packed data as bytes. Each byte is 8 bits.
Take 3 bytes at a time (24 bits in total).
The first 12 bits (from these 24) make the first number.
The next 12 bits make the second number.
Repeat for the whole data stream.
Use bitwise operations (shifting and masking) to extract the numbers.
Unpacking 12-bit data from bytes
Take 3 bytes (24 bits) from the data
First 12 bits → first number
Next 12 bits → second number
Repeat for the rest of the data
Where you see it in real life
Digital cameras: Raw image sensors often use 12-bit values for each pixel.
Medical devices: Some ECG or X-ray machines store readings as 12-bit samples.
Audio equipment: Some old sound cards use 12-bit audio samples.
Embedded systems: Sensors in cars or factories may send 12-bit data to save space.
Why it matters
Saves memory: Packing 12-bit data uses less space than 16 bits per value.
Required for reading sensor data: Many devices send data in 12-bit format.
Needed for image processing: To work with raw photos, you must unpack 12-bit pixels.
Useful in competitive programming: Sometimes, problems give you packed data to test your skills.
Worked example
Let's say you have these 3 bytes: 0xAB, 0xCD, 0xEF. You want to unpack them into two 12-bit numbers.