Designing a Portable Serialized Record

Serialization converts logical values into a specified sequence of bytes for storage or transmission. Deserialization reconstructs values from that sequence. In C, the important distinction is between an object's current memory representation and the representation your file promises to readers. A file may outlive its creating process, move to another processor, or be read by a later program version. Its meaning therefore needs to come from a documented format.


C values are encoded into specified bytes and decoded into validated C values.


Define the byte contract

A format specifies field order, field widths, integer byte order, text encoding, and how variable-length data ends. State whether a length counts bytes, characters, or records. Include a version identifier when readers need to distinguish layouts, and define what happens when a version is unsupported.


The governing requirement is a round trip that preserves logical values:


decode⁡(encode⁡(x))=x\operatorname{decode}(\operatorname{encode}(x)) = x


This applies to values supported by the format. It does not require identical pointer addresses, padding bytes, or allocated buffer capacities after reconstruction.


Representation

What the format must specify

Main limitation

Text fields

Number grammar, separators, escaping, text encoding

Separators inside data need an unambiguous representation

Explicit binary fields

Widths, byte order, lengths, value ranges

Readers must implement the byte contract precisely

Raw C structure bytes

The creating implementation's object representation

Compiler layout and process addresses are not a portable contract


Text can be portable, but merely calling a format text does not define it. Similarly, a binary format can be portable when its representation is explicit.

Encode values rather than memory accidents

A C structure can contain padding. Integer representations and field placement can differ across implementations. A pointer stores an address; copying that address does not copy the object it points to. Serialize the referenced data, or a defined identifier, instead.


For big-endian two-byte unsigned integers, the first byte carries the multiples of 256:


v=256b0+b1,0≤b0,b1≤255v = 256b_0 + b_1, \qquad 0 \leq b_0,b_1 \leq 255


Example: Assume 8-bit bytes and an available uint32_t type. After checking that value is between 0 and 65535, these fragments encode it and reconstruct it without using the host's integer byte order:


C
unsigned char encoded[2];
encoded[0] = (unsigned char)((value >> 8) & 0xffu);
encoded[1] = (unsigned char)(value & 0xffu);

uint32_t restored = ((uint32_t)encoded[0] << 8)
                  | (uint32_t)encoded[1];


Here value has type uint32_t. The casts provide a sufficiently wide intermediate for safe two-byte reconstruction, even if integer promotions make the shift operate on int; the result remains correct. A real decoder must first establish that both source bytes exist.



Reconstruct only validated records

Treat stored bytes as input to check. Establish that the fixed header exists, identify a supported version, then interpret that version's fields. Check lengths before allocating memory or consuming payload bytes, and impose an application limit on accepted sizes.


If remaining is the number of available payload bytes, test length <= remaining. This avoids an unchecked addition when testing an end position. Also validate field ranges and the promised text encoding; having enough bytes does not establish that their contents are meaningful.


A format using UTF-8 normally counts encoded bytes when specifying storage lengths. A terminating null byte is stored only if the format includes it. A reader may allocate an extra byte for a C string without consuming an extra file byte.



The write side also needs error handling: producing the intended bytes in memory does not prove they were all stored. On either side, report incomplete records instead of silently treating them as complete.

What to remember

  • Define field widths, order, byte order, encoding, and lengths explicitly.
  • Preserve logical values rather than structure padding or pointer addresses.
  • Validate available bytes, supported versions, ranges, and size limits.
  • Keep incomplete reconstruction separate from the object your program uses.

Example: Encoding a sensor event

A sensor logger stores one event using the following format. Every byte has 8 bits, and multibyte integers are unsigned and big-endian. A length prefix is a field placed before variable-length data that states its length; here it counts label bytes.

  • Version: 1 byte, with value 1.
  • Sensor identifier: 2 bytes, with value 1000.
  • Elapsed time: 4 bytes, with value 70000 ms.
  • Label length: 1 byte.
  • Label: exactly the declared number of UTF-8 bytes.

The label is lab, whose bytes are 6C 61 62. All byte listings use hexadecimal notation. The file contains no padding and no terminating null byte.


Example: Construct this event record and check whether an incomplete copy can be accepted.


a) Calculate the complete serialized record size in bytes.


First count the version, identifier, and elapsed-time fields:


1+2+4=7 bytes1+2+4=7\ \text{bytes}


These three fields occupy ________. Including the one-byte label-length field gives a fixed portion of ________.


The label contains three encoded bytes, so its length field stores 3. Add those bytes to the fixed portion:


S=1+2+4+1+3=11 bytesS=1+2+4+1+3=11\ \text{bytes}


The complete record occupies 11 bytes. No extra byte is added for a C string terminator because the file format excludes it.


b) Write the complete record as hexadecimal bytes in file order.


For the two-byte identifier, divide 1000 into multiples of 256 and a remainder:


1000=3(256)+2321000=3(256)+232


The high byte has decimal value ________, and the low byte has decimal value ________. These are hexadecimal 03 and E8, so the identifier is stored as 03 E8.


For the four-byte elapsed time, express the value using powers of 256:


70000=0(2563)+1(2562)+17(256)+11270000=0(256^3)+1(256^2)+17(256)+112


The four decimal byte values are 0, 1, 17, and 112, giving hexadecimal 00 01 11 70. The unit is milliseconds because the format assigns that meaning to the integer; no unit characters are stored.


The version is 01, the label length is 03, and the supplied label bytes are 6C 61 62. Concatenating the fields in the specified order gives the complete record:


01 03 E8 00 01 11 70 03 6C 61 62


This sequence contains 11 bytes, matching the size calculation.


c) A receiver obtains only the first 10 bytes of this record before input ends. Can it accept a complete event?


The receiver has all eight fixed bytes, so it can read the declared label length of three. Subtract the fixed portion from the received size:


available label bytes=10−8=2 bytes\text{available label bytes}=10-8=2\ \text{bytes}


Only ________ of label data are available. Compare this with the declared length:


3 bytes>2 bytes3\ \text{bytes}>2\ \text{bytes}


The record is missing ________. Therefore, the receiver must reject this input as a truncated record rather than publish a complete event. Adding a local null terminator would not recover the missing label byte or satisfy the file format.

A C program stores a structure containing an unsigned integer identifier and a pointer to an allocated name string. Its files must be readable on different compilers and CPU architectures. Which serialization strategy best meets that requirement?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A team is documenting a serialized configuration format that contains named fields and text values. Match each term to its specific role in representing or interpreting the saved data.

Match each term
A.

A stored identifier selecting which revision of the format applies

B.

A rule mapping characters to sequences of bytes

C.

A reversible substitution that distinguishes literal data from characters reserved for syntax

D.

A specification of field names, data types, and structural constraints

Version tag

Schema

Escaping

Character encoding

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A serialized inventory file has a 10-byte file header followed by 30 records. Each record contains a 4-byte identifier, a 2-byte name-length field, and exactly that many encoded name bytes. Eighteen names occupy 4 bytes each, and twelve occupy 9 bytes each. There are no padding or terminating null bytes in the file. What is its total size in bytes? Give an exact integer, to zero decimal places.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice