CodeBlanks Logo Icon CodeBlanks

Pack and unpack

  • C course
  • Intermediate
  • Lesson 104/116
  • 5 min

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.

Practice 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);.

Starter code

main.c
#include <stdio.h>

// Define lo and hi variables
// Compute packed and print
// Split low and high bytes and print

int main(void) {
    return 0;
}

Sample solution

main.c
#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;
}

Expected output

4660
lo=52 hi=18

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the pack/unpack operations

Term Meaning
hi << 8 High byte position
| lo Low byte place
& 0xFF Extract low byte
>> 8 Extract high byte

2 Complete the pack expression

Question
unsigned short packed = (hi << 8) | ____;
Answer
unsigned short packed = (hi << 8) | lo;

Explanation: (hi << 8) | lo; packs two bytes.

3 What does packed & 0xFF give?

  • The high byte
  • The low byte Correct answer
  • The whole value
  • Zero

Explanation: 0xFF keeps only the low eight bits; upper bits are zeroed.

All lessons in Intermediate