binary - Insert and extract fields from binary strings (Dissect and join binary data into/from tcl values) : '''[binary format]''' ''formatString'' ?''arg arg ...''? : '''[binary scan]''' ''string formatString'' ?''varName varName ...''? : '''[binary encode]''' ''format'' ?''-option value ...''? ''data'' : '''[binary decode]''' ''format'' ?''-option value ...''? ''data'' http://purl.org/tcl/home/man/tcl8.5/TclCmd/binary.htm ---- This is the primary command to use when [Working with binary data]. For dealing with binary data on C level see also [http://www.tcl.tk/man/tcl8.5/TclLib/ByteArrObj.htm%|%the ByteArray manpage]. See [Binary representation of numbers] or [bitstrings] for examples of usage. <> What are the issues when dealing with special values - 64 bits for instance? ---- **Examples** In a conversation in the Tcl'ers Chat about how to display the bits in a number [DKF] came up with this: ====== binary scan [binary format I $value] B32 x; set x ====== [GPS]: I use the following string to/from hex conversion procedures to store files that may contain special characters that interfere with the OS filesystem in my [Grindweb] program: ====== proc convert.string.to.hex str { binary scan $str H* hex return $hex } proc convert.hex.to.string hex { foreach c [split $hex ""] { if {![string is xdigit $c]} { return "#invalid $hex" } } binary format H* $hex } ====== ---- Q. Is there a way to display the [ASCII] equivalent of characters in a string? A. ====== set chrs "abc" binary scan [encoding convertto ascii $chrs] c* x puts $x 97 98 99 ====== results in the translation of the characters to hex being assigned to $x. If the characters are some encoding other than ASCII, just change the '''ascii''' to the appropriate encoding name. [DKF]: Also consider using `[[[scan] $str %c]]` for single characters where you want the [UNICODE] character number (which is the same as the ASCII one for ASCII characters, and the same as the ISO8859-1 codepoint too, since UNICODE is a superset of ISO8859-1 and that in turn is a superset of ASCII). ---- [AMG]: Here's a way to reverse the bit order of each ''eight-bit'' character in a string: ====== proc bit_reverse {str} { set result "" foreach char [split $str ""] { append result [binary format b8 [binary scan $char B8 bits; set bits]] } return $result } ====== <> ---- **See also** * [encoding] * [format] * [scan] * For ''transfer'' encodings: ** [base64] ** [uuencode] ** [zlib] <> Tcl syntax help | Command | Binary Data