Tcl binary data
last modified November 24, 2026 Tcl 8.6
Sooner or later a Tcl script meets data that is not meant for people: a PNG
file, a network packet, a database page, an image in memory. Such data is a
sequence of bytes, and the rules for interpreting those bytes come from a file
format or a protocol, not from the script. Tcl handles this with the
binary command, which packs Tcl values into bytes and reads them
back, and with channels that can be switched to binary mode.
This article starts with the difference between characters and bytes, then shows
binary format and binary scan, the byte order of
integers, the hex and base64 encodings, and binary channels. It ends with two
realistic tasks: reading a file header and writing a file of fixed-size records.
The binary command page lists every format
specifier.
Bytes versus characters
A character is a unit of text and a byte is eight bits of storage. In a
multi-byte encoding the two do not line up: the text Košice has six
characters but seven bytes in UTF-8, because the letter š takes two
bytes. Tcl 8.6 stores text internally as Unicode and converts it only when it
leaves the interpreter, so a script has to be explicit about which of the two it
is counting.
set city "Košice"
set bytes [encoding convertto utf-8 $city]
puts "characters: [string length $city]"
puts "utf-8 bytes: [string length $bytes]"
puts "decodes back: [expr {[encoding convertfrom utf-8 $bytes] eq $city}]"
The first string length counts characters, the second counts bytes
of the converted value, which is a byte array rather than text.
encoding convertfrom turns the bytes back into the original
string, and the comparison proves that nothing was lost. Binary data is exactly
this second kind of value: a byte array whose bytes have no character meaning.
$ tclsh bytes_chars.tcl characters: 6 utf-8 bytes: 7 decodes back: 1
Packing values with binary format
The binary format command builds a byte array from ordinary Tcl
values according to a format string. Each specifier in the string describes one
value: c is a single byte, s a 16-bit integer,
i a 32-bit integer, W a 64-bit integer and
d a double. The letters a and A store a
string of fixed width, padded with NUL bytes or with spaces.
set header [binary format "A4 i" "RIFF" 1024]
puts "header length: [string length $header] bytes"
foreach spec {c s i W d} {
puts "$spec -> [string length [binary format $spec 1]] bytes"
}
The first line packs a four-character tag and a 32-bit number, giving eight
bytes. The loop then shows the width of each numeric specifier: one byte for
c, two for s, four for i, eight for
W and d. The format string may contain several
specifiers with values following in order, which is how a header is assembled
field by field without string concatenation of numbers.
$ tclsh format_demo.tcl header length: 8 bytes c -> 1 bytes s -> 2 bytes i -> 4 bytes W -> 8 bytes d -> 8 bytes
Reading values back with binary scan
The opposite command is binary scan. It takes a byte array, a
format string and a list of variable names, and assigns one value per
specifier. Its return value is the number of conversions that were completed,
which is useful when the number of records in a buffer is not known in advance.
The specifier H* converts the whole input to lowercase hexadecimal
text, the usual way to look at raw bytes.
set record [binary format "A6 i s c" "sensor" 25 -3 7] binary scan $record "A6 i s c" name temp offset flag puts "name: <$name>" puts "temp: $temp" puts "offset: $offset" puts "flag: $flag" binary scan $record H* hex puts "hex: $hex"
The record holds a six-byte name, a 32-bit temperature, a 16-bit offset and a
one-byte flag, for thirteen bytes in total. The scan assigns all four values in
one call, including the negative offset, which comes back as -3 rather than as
an unsigned bit pattern. The last scan ignores the field structure and dumps
thirteen bytes as twenty-six hex digits; the 19 followed by three zero bytes is
25, and fdff is -3 in little-endian order.
$ tclsh scan_demo.tcl name: <sensor> temp: 25 offset: -3 flag: 7 hex: 73656e736f7219000000fdff07
Endianness and byte order modifiers
A 32-bit integer occupies four bytes, but the format does not say in which order
they go. Tcl resolves this with case: lowercase s, i
and w write little-endian numbers, where the least significant byte
comes first, and uppercase S, I and W
write big-endian numbers, where the most significant byte comes first. Big
endian is also called network byte order because most protocols use it.
set value 16909060 set little [binary format i $value] set big [binary format I $value] binary scan $little H* lh binary scan $big H* bh puts "i: $lh" puts "I: $bh" binary scan $big i v puts "big-endian bytes read as i: $v" binary scan $little I v puts "little-endian bytes read as I: $v"
The value is 0x01020304, so the little-endian form is the byte sequence 04 03 02 01 and the big-endian form is 01 02 03 04. Reading a buffer with the wrong modifier does not fail; it silently produces a different number, here 67305985 instead of 16909060. A file format or protocol specification always states its byte order, and matching it exactly is the difference between a working parser and a mysterious result.
$ tclsh endian_demo.tcl i: 04030201 I: 01020304 big-endian bytes read as i: 67305985 little-endian bytes read as I: 67305985
Hex and base64 encodings
Binary data cannot always travel as bytes. Configuration files, JSON documents,
URLs and mail messages carry text, so the bytes are encoded into a safe subset
of ASCII first. Hex writes every byte as two digits and doubles the size; base64
writes every three bytes as four characters and grows the data by a third. Tcl
provides both directions with binary encode and
binary decode.
set data [binary decode hex 89504e470d0a1a0a]
puts "hex: [binary encode hex $data]"
puts "base64: [binary encode base64 $data]"
set back [binary decode base64 [binary encode base64 $data]]
puts "round trip ok: [expr {$back eq $data}]"
puts "decoded text: [binary decode hex 48656c6c6f]"
The eight bytes in the example are the beginning of a PNG file, the signature
that every PNG starts with. Their base64 form is what a data URL or a JSON field
would contain. The round trip compares the decoded value with the original byte
array, and the last line shows that hex is also a convenient way to spell short
text: 48656c6c6f is Hello. Encodings change the
representation, never the bytes.
$ tclsh encode_demo.tcl hex: 89504e470d0a1a0a base64: iVBORw0KGgo= round trip ok: 1 decoded text: Hello
Binary channels
Writing bytes to a file needs one more step. By default a channel translates
line endings and converts between the external encoding and Tcl's internal
strings, which is right for text and wrong for binary data.
fconfigure $ch -translation binary turns both behaviours off, so
every byte is passed through untouched. The same option applies to sockets and
pipes.
set path [file join [pwd] sample.bin] set ch [open $path w] fconfigure $ch -translation binary puts -nonewline $ch [binary format "A4 i" "DATA" 42] close $ch set ch [open $path r] fconfigure $ch -translation binary set content [read $ch] close $ch binary scan $content "A4 i" tag size puts "tag: $tag" puts "size: $size" puts "read [string length $content] bytes"
The file is written with puts -nonewline, because a newline would
add a byte that the format does not contain. It is then reopened, switched to
binary mode and read in one call with read, which
returns a byte array of exactly eight bytes. Scanning the buffer recovers the tag
and the number. Forgetting the binary configuration is the classic bug in this
area: the newline translation can strip carriage returns, and the encoding
conversion can replace every byte above 0x7f.
$ tclsh channel_demo.tcl tag: DATA size: 42 read 8 bytes
Parsing a small binary header
Real formats start with a signature followed by fields whose position is fixed.
A PNG file, for instance, begins with eight signature bytes and then a chunk
whose length and type come first. Parsing such a header means skipping over
known fields with x and reading the rest with the right specifiers.
The example builds the same structure in memory so that the parse can be checked
against known values.
set signature [binary format H* 89504e470d0a1a0a]
set chunk [binary format "I A4 I I c c c c c" 13 "IHDR" 800 600 8 2 0 0 0]
set header $signature$chunk
puts "header bytes: [string length $header]"
binary scan $header "H16 x4 A4 I I c c c c c" magic type w h depth color comp filt inter
puts "signature: $magic"
puts "chunk: $type ${w}x${h}"
puts "depth $depth, color type $color, interlace $inter"
The chunk is written in big-endian order because that is what the PNG
specification requires, starting with the data length 13 and the four-character
type. The scan reads sixteen hex digits for the signature, skips the four-byte
length with x4, then reads the type, the width, the height and the
five single-byte fields. The real format continues with a CRC after the data;
the example stops before it, but the technique of skipping and reading fields in
order is the same.
$ tclsh header_demo.tcl header bytes: 29 signature: 89504e470d0a1a0a chunk: IHDR 800x600 depth 8, color type 2, interlace 0
Writing binary data to a file
A file of fixed-size records is the natural next step. Each record is written with the same format string, so its length never changes and a reader can jump from one to the next. The writer below stores a name padded to eight bytes and a 32-bit score. The reader loads the whole file, then scans record after record and shortens the buffer until nothing is left.
set path [file join [pwd] scores.bin]
set ch [open $path w]
fconfigure $ch -translation binary
foreach {name score} {Jane 91 Ravi 78 Ola 85} {
puts -nonewline $ch [binary format "A8 i" $name $score]
}
close $ch
set ch [open $path r]
fconfigure $ch -translation binary
set content [read $ch]
close $ch
set count 0
while {[binary scan $content "A8 i" name score] == 2} {
puts "[string trim $name]: $score"
incr count
set content [string range $content 12 end]
}
puts "$count records, [file size $path] bytes"
The writer uses A8, which pads short names with spaces; that is why
the reader can strip them with string trim and get the original
name back. Each record is twelve bytes, so the loop cuts twelve bytes off the
front after every successful scan, and binary scan returns 0 when
the buffer is empty and the loop ends. file size
confirms the total of thirty-six bytes. The same pattern scales to thousands of
records, with seek used instead of reading the whole
file when only one record is needed.
$ tclsh records_demo.tcl Jane: 91 Ravi: 78 Ola: 85 3 records, 36 bytes
Source
The Tcl 8.6 manual lists every specifier of binary format and
binary scan, including the H, a,
A and x forms used above, together with the channel
options that control translation and encoding.
This article moved from characters to bytes: packing values with
binary format, reading them with binary scan,
controlling byte order, converting to hex and base64, and passing raw bytes
through channels. The two closing examples, a PNG-style header and a file of
records, use the same handful of commands that any binary parser needs. Related
material is on the binary command page and in the
processes article, where such bytes arrive from
another program.
Author
List all Tcl Tutorials.