C
Pack and unpack
Learn data compression with bit pack and unpack.
Pack: merge two bytes
Packing places two small values inside one larger value. To pack two bytes into a short you use shift and OR.
Example: unsigned short packed = (hi << 8) | lo;. Here hi is the high byte, lo the low byte. hi is shifted eight places left to reach the high byte position. Then it is OR'ed with lo to place the low byte. The result is a short with the two bytes side by side. This technique compresses color codes, hardware registers and network packets.
Unpack: split bytes
Unpacking splits a packed value into its components. To get the low byte use & 0xFF; to get the high byte use >> 8.
Example: unsigned char unpack_lo = packed & 0xFF; gives the low byte. unsigned char unpack_hi = packed >> 8; gives the high byte. 0xFF is 11111111 in binary; AND keeps only the low eight bits and zeroes the upper bits. Shifting moves the high byte down to the low byte position. Together these two operations extract every component of a packed value. They are used constantly in network protocols and file formats.
Exercise Write pack and unpack
Declare unsigned char lo = 0x34; and unsigned char hi = 0x12;. Compute unsigned short packed = (hi << 8) | lo;. Print with printf("%u\n", packed);. Compute unsigned char unpack_lo = packed & 0xFF; and unsigned char unpack_hi = packed >> 8;. Print with printf("lo=%u hi=%u\n", unpack_lo, unpack_hi);.
Show example solution
#include <stdio.h>
int main(void) {
unsigned char lo = 0x34;
unsigned char hi = 0x12;
unsigned short packed = (hi << 8) | lo;
printf("%u\n", packed);
unsigned char unpack_lo = packed & 0xFF;
unsigned char unpack_hi = packed >> 8;
printf("lo=%u hi=%u\n", unpack_lo, unpack_hi);
return 0;
}
Test yourself
-
Match the pack/unpack operations
- hi << 8
- High byte position
- | lo
- Low byte place
- & 0xFF
- Extract low byte
- >> 8
- Extract high byte
-
Complete the pack expression
unsigned short packed = (hi << 8) | ____;
Show answer
unsigned short packed = (hi << 8) | lo;
-
What does packed & 0xFF give?
- The high byte
- The low byte
- The whole value
- Zero
Show answer
The low byte — 0xFF keeps only the low eight bits; upper bits are zeroed.
Next lesson: Summary - Advanced bitwise