Simvik

Variable-length integer

Encode a 32-bit value in as few bytes as it needs. A medium embedded C problem (Protocols, framing and checksums), run and graded in the browser.

medium · Protocols, framing and checksums · encoding · leb128

Protocol Buffers and MQTT encode integers seven bits at a time, least significant group first. Each byte carries 7 bits of the value in bits 6..0, and bit 7 is set when more bytes follow.

Encode value into out and return the number of bytes written (1 to 5). For example 300 is AC 02.

Starter code

size_t varint_encode(uint32_t value, uint8_t *out) {
  // 7 bits per byte, low group first, bit 7 = "more bytes follow".
  return 0;
}

Example tests

Two bytes

uint8_t out[5];
size_t n = varint_encode(300, out);
for (size_t i = 0; i < n; i++) printf("%02X ", out[i]);
printf("\n");

Expected output:

AC 02

One byte

uint8_t out[5];
size_t n = varint_encode(127, out);
for (size_t i = 0; i < n; i++) printf("%02X ", out[i]);
printf("\n");

Expected output:

7F

Learn it first

More Protocols, framing and checksums problems