Opening a File in Binary Mode

A binary stream reads bytes and writes bytes. This preserves exact line endings and encoded data for a format parser or archive.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Inspect a short header
  2. Choose the correct boundary
  3. Keep line-ending bytes and offsets intact
  4. Decide when decoding should happen

Inspect a short header

Reading a length field from binary input supplies bytes such as 00 04. Treating that data as a text string first can introduce decoding concerns unrelated to the length. Use binary byte order to interpret the field.

Choose the correct boundary

A text parser usually wants decoded characters. A file copier or a reader validating absolute byte offsets can work on bytes directly. Line numbers and byte offsets distinguish the diagnostics suitable for those two paths.[1]

Keep line-ending bytes and offsets intact

A binary read of bytes 41 0D 0A 42 returns all four values. A text reader with universal newline translation can expose A, a logical newline and B. Byte format readers should use binary mode when a field's position is defined in bytes. See line ending representations.

Offset 0: 41
Offset 1: 0D
Offset 2: 0A
Offset 3: 42
Binary length: 4

Decide when decoding should happen

A binary record can contain a length header and a UTF-8 text payload. Read the header and number of bytes first, then decode the payload under its format rule. Test an embedded zero byte for binary identity and a multibyte character for decoding.

References

  1. Python Software Foundation, io: Core Tools for Working with Streams ↩