binary(n)
binary(n) β Tcl Built-In Commands π
okay bestie, welcome to the binary(n) manual page. It's giving Tcl built-in, it's giving byte-level glamour, and it's literally all about inserting and extracting fields from binary strings. No cap. π
β¨ NAME β¨
binary β Insert and extract fields from binary strings π
π SYNOPSIS π
here's the vibe check, four ways to call it:
binary decode format ?-option value ...? data
binary encode format ?-option value ...? data
binary format formatString ?arg arg ...?
binary scan string formatString ?varName varName ...?
π¦ DESCRIPTION π¦
This command provides facilities for manipulating binary data. The subcommand binary format creates a binary string from normal Tcl values. For example, given the values 16 and 22, on a 32-bit architecture, it might produce an 8-byte binary string consisting of two 4-byte integers, one for each of the numbers. The subcommand binary scan, does the opposite: it extracts data from a binary string and returns it as ordinary Tcl string values. The binary encode and binary decode subcommands convert binary data to or from string encodings such as base64 (used in MIME messages for example). β¨
Note that other operations on binary data, such as taking a subsequence of it, getting its length, or reinterpreting it as a string in some encoding, are done by other Tcl commands (respectively string range, string length and encoding convertfrom in the example cases). A binary string in Tcl is merely one where all the characters it contains are in the range \u0000-\u00FF. π
πΈ BINARY ENCODE AND DECODE πΈ
When encoding binary data as a readable string, the starting binary data is passed to the binary encode command, together with the name of the encoding to use and any encoding-specific options desired. Data which has been encoded can be converted back to binary form using binary decode. The binary encode command raises an error if the data argument is not binary data. The following formats and options are supported. slay π
base64
The base64 binary encoding is commonly used in mail messages and XML documents, and uses mostly upper and lower case letters and digits. It has the distinction of being able to be rewrapped arbitrarily without losing information. iconic π
During encoding, the following options are supported:
-maxlenlength β Indicates that the output should be split into lines of no more than length characters. By default, lines are not split.-wrapcharcharacter β Indicates that, when lines are split because of the-maxlenoption, character should be used to separate lines. By default, this is a newline character,\n.
During decoding, the following options are supported:
-strictβ Instructs the decoder to throw an error if it encounters any characters that are not strictly part of the encoding itself. Otherwise it ignores them. RFC 2045 calls for base64 decoders to be non-strict.
hex
The hex binary encoding converts each byte to a pair of hexadecimal digits that represent the byte value as a hexadecimal integer. When encoding, lower characters are used. When decoding, upper and lower characters are accepted. lowkey π₯
No options are supported during encoding. During decoding, the following options are supported:
-strictβ Instructs the decoder to throw an error if it encounters whitespace characters. Otherwise it ignores them.
uuencode
The uuencode binary encoding used to be common for transfer of data between Unix systems and on USENET, but is less common these days, having been largely superseded by the base64 binary encoding. throwback vibes π«Ά
During encoding, the following options are supported (though changing them may produce files that other implementations of decoders cannot process):
-maxlenlength β Indicates the maximum number of characters to produce for each encoded line. The valid range is 5 to 85. Line lengths outside that range cannot be accommodated by the encoding format. The default value is 61.-wrapcharcharacter β Indicates the character(s) to use to mark the end of each encoded line. Acceptable values are a sequence of zero or more characters from the set {\x09(TAB),\x0B(VT),\x0C(FF),\x0D(CR) } followed by zero or one newline\x0A(LF). Any other values are rejected because they would generate encoded text that could not be decoded. The default value is a single newline.
During decoding, the following options are supported:
-strictβ Instructs the decoder to throw an error if it encounters anything outside of the standard encoding format. Without this option, the decoder tolerates some deviations, mostly to forgive reflows of lines between the encoder and decoder.
Note that neither the encoder nor the decoder handle the header and footer of the uuencode format. π
π BINARY FORMAT π
The binary format command generates a binary string whose layout is specified by the formatString and whose contents come from the additional arguments. The resulting binary value is returned. main character energy β¨
The formatString consists of a sequence of zero or more field specifiers separated by zero or more spaces. Each field specifier is a single type character followed by an optional flag character followed by an optional numeric count. Most field specifiers consume one argument to obtain the value to be formatted. The type character specifies how the value is to be formatted. The count typically indicates how many items of the specified type are taken from the value. If present, the count is a non-negative decimal integer or *, which normally indicates that all of the items in the value are to be used. If the number of arguments does not match the number of fields in the format string that consume arguments, then an error is generated. The flag character is ignored for binary format. π
Here is a small example to clarify the relation between the field specifiers and the arguments:
binary format d3d {1.0 2.0 3.0 4.0} 0.1
The first argument is a list of four numbers, but because of the count of 3 for the associated field specifier, only the first three will be used. The second argument is associated with the second field specifier. The resulting binary string contains the four numbers 1.0, 2.0, 3.0 and 0.1.
Each type-count pair moves an imaginary cursor through the binary data, storing bytes at the current position and advancing the cursor to just after the last byte stored. The cursor is initially at position 0 at the beginning of the data. The type may be any one of the following characters:
aβ Stores a byte string of length count in the output string. Every character is taken as modulo 256 (i.e. the low byte of every character is used, and the high byte discarded) so when storing character strings not wholly expressible using the characters\u0000-\u00ff, theencoding converttocommand should be used first to change the string into an external representation if this truncation is not desired (i.e. if the characters are not part of the ISO 8859-1 character set.) If arg has fewer than count bytes, then additional zero bytes are used to pad out the field. If arg is longer than the specified length, the extra characters will be ignored. If count is*, then all of the bytes in arg will be formatted. If count is omitted, then one character will be formatted. For example, the command:
binary format a7a*a alpha bravo charlie
will return a binary string equivalent to:
alpha\000\000bravoc
the command:
binary format a* [encoding convertto utf-8 \u20ac]
will return a binary string equivalent to:
\342\202\254
(which is the UTF-8 byte sequence for a Euro-currency character), and the command:
binary format a* [encoding convertto iso8859-15 \u20ac]
will return a binary string equivalent to:
\244
(which is the ISO 8859-15 byte sequence for a Euro-currency character). Contrast these last two with:
binary format a* \u20ac
which returns a binary string equivalent to:
\254
(i.e. \xAC) by truncating the high-bits of the character, and which is probably not what is desired. π
Aβ This form is the same asaexcept that spaces are used for padding instead of nulls. For example,
binary format A6A*A alpha bravo charlie
will return
alpha bravoc
bβ Stores a string of count binary digits in low-to-high order within each byte in the output binary string. Arg must contain a sequence of 1 and 0 characters. The resulting bytes are emitted in first to last order with the bits being formatted in low-to-high order within each byte. If arg has fewer than count digits, then zeros will be used for the remaining bits. If arg has more than the specified number of digits, the extra digits will be ignored. If count is*, then all of the digits in arg will be formatted. If count is omitted, then one digit will be formatted. If the number of bits formatted does not end at a byte boundary, the remaining bits of the last byte will be zeros. For example,
binary format b5b* 11100 111000011010
will return a binary string equivalent to:
\x07\x87\x05
Bβ This form is the same asbexcept that the bits are stored in high-to-low order within each byte. For example,
binary format B5B* 11100 111000011010
will return a binary string equivalent to:
\xE0\xE1\xA0
Hβ okay so this one stores a string ofcounthexadecimal digits in high-to-low within each byte of the output binary string. Arg must be a sequence of characters from the set β0123456789abcdefABCDEFβ. The resulting bytes get emitted first-to-last, with the hex digits formatted high-to-low inside each byte. If arg has fewer thancountdigits, then zeros fill in the remaining digits (no big deal π ). If arg has more than the specified number of digits, the extra digits just get ignored π. Ifcountis β*β, then all of the digits in arg get formatted. Ifcountis omitted, then one digit gets formatted. And if the number of digits formatted doesn't end at a byte boundary, the remaining bits of the last byte are zeros, periodt. For example,
binary format H3H*H2 ab DEF 987
will return a binary string equivalent to:
\xAB\x00\xDE\xF0\x98
hβ this form is the same asH, except the digits are stored low-to-high order within each byte. Ngl this is seldom required. For example,
binary format h3h*h2 AB def 987
will return a binary string equivalent to:
\xBA\x00\xED\x0F\x89
cβ stores one or more 8-bit integer values in the output string. If nocountis specified, then arg must consist of an integer value. Ifcountis specified, arg must consist of a list containing at least that many integers. The low-order 8 bits of each integer get stored as a one-byte value at the cursor position. Ifcountis β*β, then all of the integers in the list are formatted. If the number of elements in the list is greater thancount, then the extra elements are ignored, bye π. For example,
binary format c3cc* {3 -3 128 1} 260 {2 5}
will return a binary string equivalent to:
\x03\xFD\x80\x04\x02\x05
whereas:
binary format c {2 5}
will generate an error. not her catching an error like that π
sβ this form is the same asc, except it stores one or more 16-bit integers in little-endian byte order in the output string. The low-order 16 bits of each integer get stored as a two-byte value at the cursor position, with the least significant byte stored first. For example,
binary format s3 {3 -3 258 1}
will return a binary string equivalent to:
\x03\x00\xFD\xFF\x02\x01
Sβ this form is the same ass, except it stores one or more 16-bit integers in big-endian byte order in the output string. For example,
binary format S3 {3 -3 258 1}
will return a binary string equivalent to:
\x00\x03\xFF\xFD\x01\x02
tβ this form (mnemonically tiny) is the same assandS, except it stores the 16-bit integers in the output string in the native byte order of the machine where the Tcl script is running. To figure out what the native byte order of the machine actually is, go look at thebyteOrderelement of thetcl_platformarray π¦.iβ this form is the same asc, except it stores one or more 32-bit integers in little-endian byte order in the output string. The low-order 32 bits of each integer get stored as a four-byte value at the cursor position, with the least significant byte stored first. For example,
binary format i3 {3 -3 65536 1}
will return a binary string equivalent to:
\x03\x00\x00\x00\xFD\xFF\xFF\xFF\x00\x00\x01\x00
Iβ this form is the same asi, except it stores one or more 32-bit integers in big-endian byte order in the output string. For example,
binary format I3 {3 -3 65536 1}
will return a binary string equivalent to:
\x00\x00\x00\x03\xFF\xFF\xFF\xFD\x00\x01\x00\x00
nβ this form (mnemonically number or normal) is the same asiandI, except it stores the 32-bit integers in the output string in the native byte order of the machine where the Tcl script is running. To determine what the native byte order of the machine is, refer to thebyteOrderelement of thetcl_platformarray β¨.wβ this form is the same asc, except it stores one or more 64-bit integers in little-endian byte order in the output string. The low-order 64 bits of each integer get stored as an eight-byte value at the cursor position, with the least significant byte stored first. For example,
binary format w 7810179016327718216
will return the binary string HelloTcl. obsessed with that tbh π
Wβ this form is the same asw, except it stores one or more 64-bit integers in big-endian byte order in the output string. For example,
binary format Wc 4785469626960341345 110
will return the binary string BigEndian.
mβ this form (mnemonically the mirror ofw) is the same aswandW, except it stores the 64-bit integers in the output string in the native byte order of the machine where the Tcl script is running. To determine what the native byte order of the machine is, refer to thebyteOrderelement of thetcl_platformarray π.fβ this form is the same asc, except it stores one or more single-precision floating point numbers in the machine's native representation in the output string. Heads up bestie, this representation is not portable across architectures, so it should not be used to communicate floating point numbers across the network. The size of a floating point number may vary across architectures, so the number of bytes that get generated may vary too. If the value overflows the machine's native representation, then the value ofFLT_MAXas defined by the system gets used instead. And because Tcl uses double-precision floating point numbers internally, there may be some loss of precision in the conversion to single-precision π. For example, on a Windows system running on an Intel Pentium processor,
binary format f2 {1.6 3.4}
will return a binary string equivalent to:
\xCD\xCC\xCC\x3F\x9A\x99\x59\x40
rβ this form (mnemonically real) is the same asf, except it stores the single-precision floating point numbers in little-endian order. This conversion only produces meaningful output when used on machines which use the IEEE floating point representation (very common, but not universal, iykyk).Rβ this form is the same asr, except it stores the single-precision floating point numbers in big-endian order.dβ this form is the same asf, except it stores one or more double-precision floating point numbers in the machine's native representation in the output string. For example, on a Windows system running on an Intel Pentium processor,
binary format d1 {1.6}
will return a binary string equivalent to:
\x9A\x99\x99\x99\x99\x99\xF9\x3F
qβ this form (mnemonically the mirror ofd) is the same asd, except it stores the double-precision floating point numbers in little-endian order. This conversion only produces meaningful output when used on machines which use the IEEE floating point representation (very common, but not universal π«Ά).Qβ this form is the same asq, except it stores the double-precision floating point numbers in big-endian order.xβ storescountnull bytes in the output string. Ifcountis not specified, it stores one null byte. Ifcountis β*β, it generates an error. This type does not consume an argument. For example,
binary format a3xa3x2a3 abc def ghi
will return a binary string equivalent to:
abc\000def\000\000ghi
Xβ moves the cursor backcountbytes in the output string. Ifcountis β*β or is larger than the current cursor position, then the cursor gets positioned at location0, so the next byte stored will be the first byte in the result string. Ifcountis omitted, then the cursor moves back one byte. This type does not consume an argument. For example,
binary format a3X*a3X2a3 abc def ghi
will return dghi.
@β moves the cursor to the absolute location in the output string specified bycount. Position0refers to the first byte in the output string. Ifcountrefers to a position beyond the last byte stored so far, then null bytes get placed in the uninitialized locations and the cursor gets placed at the specified location. Ifcountis β*β, then the cursor moves to the current end of the output string. Ifcountis omitted, then an error gets generated. This type does not consume an argument. For example,
binary format a5@2a1@*a3@10a1 abcde f ghi j
will return
abfdeghi\000\000j
π BINARY SCAN π
The binary scan command parses fields from a binary string, returning the number of conversions performed. String gives the input bytes to be parsed, and formatString tells it how to parse them. An error gets raised if string is anything other than a valid binary data value π¨. Each varName gives the name of a variable; when a field is scanned from string, the result gets assigned to the corresponding variable.
Same energy as binary format: the formatString is a sequence of zero or more field specifiers separated by zero or more spaces. Each field specifier is a single type character, followed by an optional flag character, followed by an optional numeric count. Most field specifiers consume one argument to grab the variable into which the scanned values should be placed. The type character says how the binary data is to be interpreted. The count typically indicates how many items of the specified type get taken from the data. If present, the count is a non-negative decimal integer or β*β, which normally means that all of the remaining items in the data are to be used. If there aren't enough bytes left after the current cursor position to satisfy the current field specifier, then the corresponding variable is left untouched and binary scan returns immediately with the number of variables that were set. If there aren't enough arguments for all of the fields in the format string that consume arguments, then an error gets generated. The flag character βuβ may be given to cause some types to be read as unsigned values β the flag is accepted for all field types but is ignored for non-integer fields π.
A similar example as with binary format should explain the relation between field specifiers and arguments in case of the binary scan subcommand:
binary scan $bytes s3s first second
So this command β assuming the binary string chilling in the variable bytes is long enough β hands a list of three integers to the variable first, and one single value to the variable second. And if bytes has fewer than 8 bytes in it (that's four 2-byte integers, bestie, do the math π
), then second gets no assignment at all. And if bytes has fewer than 6 bytes (three 2-byte integers), then first gets nothing either. So like:
puts [binary scan abcdefg s3s first second]
puts $first
puts $second
and that prints (assuming neither variable was set before this, obviously):
1
25185 25699 26213
can't read "second": no such variable
π¨ Important note alert π¨ thec,s, andS(and alsoiandIwhen you're on a 64bit system) get scanned into long data size values. And when that happens, any value with its high bit set (0x80for chars,0x8000for shorts,0x80000000for ints) gets sign extended. So this is what goes down:
set signShort [binary format s1 0x8000]
binary scan $signShort s1 val; # val == 0xFFFF8000
If you want unsigned values instead, just slap the "u" flag character right after the field type. Like, to read an unsigned short value:
set signShort [binary format s1 0x8000]
binary scan $signShort su1 val; # val == 0x00008000
Okay so every type-count pair moves an imaginary cursor through the binary data, reading bytes from wherever the cursor is currently sitting. The cursor starts at position 0, at the very beginning of the data. And the type can be any one of these iconic little characters:
aβ the data is a byte string of length count. If count is "*", then all of the remaining bytes in string get scanned into the variable. If count is omitted, then it's just one byte. Every byte scanned gets interpreted as characters in the range\u0000-\u00ff, which means you're gonna need theencoding convertfromcommand if the string isn't a binary string or a string encoded in ISO 8859-1. For example,
binary scan abcde\000fghi a6a10 var1 var2
returns 1, with the string equivalent to abcde\000 stored in var1, and var2 left completely unmodified. And then:
binary scan \342\202\254 a* var1
set var2 [encoding convertfrom utf-8 $var1]
stores a Euro-currency character in var2. Slay πΆβ¨
Aβ same energy asa, except trailing blanks and nulls get stripped off the scanned value before it's stored in the variable. For example,
binary scan "abc efghi \000" A* var1
returns 1 with abc efghi stored in var1. Clean. π§Ό
bβ the data gets turned into a string of count binary digits in low-to-high order, represented as a sequence of "1" and "0" characters. The data bytes are scanned first to last, with the bits taken in low-to-high order within each byte. Any extra bits left over in the last byte are just ignored, whatever. If count is "*", then all of the remaining bits in string get scanned. If count is omitted, then one bit. For example,
binary scan \x07\x87\x05 b5b* var1 var2
returns 2, with 11100 stored in var1 and 1110000110100000 stored in var2.
Bβ same asb, except the bits are taken in high-to-low order within each byte. For example,
binary scan \x70\x87\x05 B5B* var1 var2
returns 2, with 01110 stored in var1 and 1000011100000101 stored in var2.
Cβ similar toA, except it scans the data from the start and terminates at the first null (that's C string semantics for you π« ). For example,
binary scan "abc\000efghi" C* var1
returns 1 with abc stored in var1.
Hβ the data gets turned into a string of count hexadecimal digits in high-to-low order, represented as a sequence of characters from the set "0123456789abcdef". The data bytes are scanned first to last, with the hex digits taken in high-to-low order within each byte. Any extra bits in the last byte get ignored. If count is "*", then all of the remaining hex digits in string get scanned. If count is omitted, then one hex digit. For example,
binary scan \x07\xC6\x05\x1F\x34 H3H* var1 var2
returns 2, with 07c stored in var1 and 051f34 stored in var2.
hβ same asH, except the digits are taken in reverse (low-to-high) order within each byte. For example,
binary scan \x07\x86\x05\x12\x34 h3h* var1 var2
returns 2, with 706 stored in var1 and 502143 stored in var2.
Just so you know, most code that wants to parse hexadecimal digits from multiple bytes in order should be using theHformat. That's the one, bestie.his not it for that job.
cβ the data gets turned into count 8-bit signed integers and stored in the corresponding variable as a list, or as unsigned ifuis placed immediately after thec. If count is "*", then all the remaining bytes in string get scanned. If count is omitted, then one 8-bit integer. For example,
binary scan \x07\x86\x05 c2c* var1 var2
returns 2, with 7 -122 stored in var1 and 5 stored in var2. And note that the integers returned are signed unless you use cu in place of c. π―
sβ the data is interpreted as count 16-bit signed integers represented in little-endian byte order, or as unsigned ifuis placed immediately after thes. The integers get stored in the corresponding variable as a list. If count is "*", then all the remaining bytes in string get scanned. If count is omitted, then one 16-bit integer. For example,
binary scan \x05\x00\x07\x00\xF0\xFF s2s* var1 var2
returns 2, with 5 7 stored in var1 and -16 stored in var2. Note that the integers returned are signed unless su is used in place of s.
Sβ same assexcept the data is interpreted as count 16-bit integers in big-endian byte order. For example,
binary scan \x00\x05\x00\x07\xFF\xF0 S2S* var1 var2
returns 2, with 5 7 stored in var1 and -16 stored in var2.
tβ the data is interpreted as count 16-bit signed integers in the native byte order of the machine running the Tcl script, or as unsigned ifuis placed immediately after thet. Otherwise it's identical tosandS. Wanna know what your machine's native byte order actually is? Go check thebyteOrderelement of thetcl_platformarray. π§iβ the data is interpreted as count 32-bit signed integers in little-endian byte order, or as unsigned ifuis placed immediately after thei. The integers get stored in the corresponding variable as a list. If count is "*", then all the remaining bytes in string get scanned. If count is omitted, then one 32-bit integer. For example,
set str \x05\x00\x00\x00\x07\x00\x00\x00\xF0\xFF\xFF\xFF
binary scan $str i2i* var1 var2
returns 2, with 5 7 stored in var1 and -16 stored in var2. Note that the integers returned are signed unless iu is used in place of i.
Iβ this form is the same asIexcept that the data is interpreted as count 32-bit signed integers represented in big-endian byte order, or as unsigned ifuis placed immediately after theI. For example,
set str \x00\x00\x00\x05\x00\x00\x00\x07\xFF\xFF\xFF\xF0
binary scan $str I2I* var1 var2
returns 2, with 5 7 stored in var1 and -16 stored in var2.
nβ the data is interpreted as count 32-bit signed integers in the native byte order of the machine running the Tcl script, or as unsigned ifuis placed immediately after then. Otherwise identical toiandI. Again, to figure out your machine's native byte order, look at thebyteOrderelement of thetcl_platformarray. π«wβ the data is interpreted as count 64-bit signed integers in little-endian byte order, or as unsigned ifuis placed immediately after thew. The integers get stored in the corresponding variable as a list. If count is "*", then all the remaining bytes in string get scanned. If count is omitted, then one 64-bit integer. For example,
set str \x05\x00\x00\x00\x07\x00\x00\x00\xF0\xFF\xFF\xFF
binary scan $str wi* var1 var2
returns 2, with 30064771077 stored in var1 and -16 stored in var2.
Wβ same aswexcept the data is interpreted as count 64-bit signed integers in big-endian byte order, or as unsigned ifuis placed immediately after theW. For example,
set str \x00\x00\x00\x05\x00\x00\x00\x07\xFF\xFF\xFF\xF0
binary scan $str WI* var1 var2
returns 2, with 21474836487 stored in var1 and -16 stored in var2.
mβ the data is interpreted as count 64-bit signed integers in the native byte order of the machine running the Tcl script, or as unsigned ifuis placed immediately after them. Otherwise identical towandW. And yeah,byteOrderelement of thetcl_platformarray, you know the drill by now. πfβ the data is interpreted as count single-precision floating point numbers in the machine's native representation. The floating point numbers get stored in the corresponding variable as a list. If count is "*", then all the remaining bytes in string get scanned. If count is omitted, then one single-precision floating point number. Heads up though: the size of a floating point number may vary across architectures, so the number of bytes that actually get scanned may vary too. And if the data doesn't represent a valid floating point number, the resulting value is undefined and compiler dependent π β so like, don't come for it. For example, on a Windows system running on an Intel Pentium processor,
binary scan \x3F\xCC\xCC\xCD f var1
returns 1, with 1.6000000238418579 stored in var1.
rβ same asfexcept the data is interpreted as count single-precision floating point numbers in little-endian order. Just so you're aware, this conversion is not portable to the minority of systems that aren't using IEEE floating point representations. π«ΆRβ same asfbut the data is read as count single-precision floating point numbers in big-endian order. Heads up bestie: this conversion is not portable to the minority of systems that don't use IEEE floating point representations. πdβ same asf, except the data is interpreted as count double-precision floating point numbers in the machine's native representation. So like, on a Windows system running on an Intel Pentium processor:
binary scan \x9A\x99\x99\x99\x99\x99\xF9\x3F d var1
will return 1 with 1.6000000000000001 stored in var1. periodt β¨
qβ same asd, but the data is interpreted as count double-precision floating point number in little-endian order. Again, this conversion is not portable to the minority of systems not using IEEE floating point representations. π«ΆQβ same asd, except the data is interpreted as count double-precision floating point number in big-endian order. Same deal: not portable to the minority of systems not using IEEE floating point representations. πxβ moves the cursor forward count bytes in string. If count is"*"or is larger than the number of bytes after the current cursor position, then the cursor lands after the last byte in string. If count is omitted, the cursor just moves forward one byte. Ngl this type does not consume an argument. For example:
binary scan \x01\x02\x03\x04 x2H* var1
will return 1 with 0304 stored in var1. slay πΈ
Xβ moves the cursor back count bytes in string. If count is"*"or is larger than the current cursor position, then the cursor gets positioned at location0, so the next byte scanned will be the first byte in string. If count is omitted then the cursor moves back one byte. Also does not consume an argument, iykyk. Example time:
binary scan \x01\x02\x03\x04 c2XH* var1 var2
will return 2 with 1 2 stored in var1 and 020304 stored in var2. iconic π
@β moves the cursor to the absolute location in the data string specified by count. Quick note: position0refers to the first byte in string. If count points to a position beyond the end of string, then the cursor is positioned after the last byte. And if count is omitted, then an error will be generated β no vibes, just error. For example:
binary scan \x01\x02\x03\x04 c2@1H* var1 var2
will return 2 with 1 2 stored in var1 and 020304 stored in var2. β¨
π PORTABILITY ISSUES π
Okay so listen up, this part matters bestie. The r, R, q and Q conversions will only work reliably for transferring data between computers that are all using IEEE floating point representations. That is very common β like, extremely common β but it is not universal. π
So if you wanna transfer floating-point numbers portably between all architectures, use their textual representation instead (as produced by format). That's the move. π
π EXAMPLES π
Here's a procedure to write a Tcl string to a binary-encoded channel as UTF-8 data preceded by a length word:
proc writeString {channel string} {
set data [encoding convertto utf-8 $string]
puts -nonewline [binary format Ia* \
[string length $data] $data]
}
And this procedure reads a string from a channel that was written by the previously presented writeString procedure β they're a matching set, they're literally soulmates:
proc readString {channel} {
if {![binary scan [read $channel 4] I length]} {
error "missing length"
}
set data [read $channel $length]
return [encoding convertfrom utf-8 $data]
}
Then this one converts the contents of a file (named in the variable filename) to base64 and prints them:
set f [open $filename rb]
set data [read $f]
close $f
puts [binary encode base64 -maxlen 64 $data]
obsessed. all of these ate. π
π SEE ALSO π
β KEYWORDS β
binary, format, scan
okay that's the whole page bestie, you're officially a binary girlie now π¦ this one's from the Tcl manual, version 8.0, and it's the binary(n) page itself β she's been serving since forever and she shows no signs of stopping. mwah π go forth and binary scan responsibly, no cap. π«Ά
π¦ where this page comes from
- alpine 3.23: tcl9-doc 9.0.3-r0 Β· TCL
- alpine 3.24: tcl9-doc 9.0.3-r2 Β· TCL
- fedora 43: tcl-doc 1:9.0.2-1.fc43 Β· TCL AND GPL-3.0-or-later WITH Bison-exception-2.2 AND BSD-3-Clause
- fedora 44: tcl-doc 1:9.0.2-1.fc44 Β· TCL AND GPL-3.0-or-later WITH Bison-exception-2.2 AND BSD-3-Clause
- nixos 26.05: tcl 9.0.3
- Copyright (c) 1997 Sun Microsystems, Inc
- Copyright (c) 2008 Donal K. Fellows
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms