Search code examples
tcltclsh

Tcl/tk binary output differs from input


The script creates a binary file containing the binary data but the output is wrong, it adds binary data. What is happening?

#!/usr/bin/tclsh

if 0 {

# One pixel BMP image
0000000 4d42 003a 0000 0000 0000 0036 0000 0028
0000010 0000 0001 0000 0001 0000 0001 0018 0000
0000020 0000 0004 0000 104d 0000 104d 0000 0000
0000030 0000 0000 0000 b8b8 00e9
000003a
}
set hex1 "424d3a00000000000000360000002800"
set hex2 "00000100000001000000010018000000"
set hex3 "0000040000004d1000004d1000000000"
set hex4 "000000000000b8b800e9"
set fp [open text.bin w]
set outBinData [binary format H* $hex1$hex2$hex3$hex4]
puts "Format done: $outBinData"
puts -nonewline $fp $outBinData
close $fp
set fp [open text.bin r]
set inBinData [read $fp]
close $fp`

Solution

  • You're forgetting to tell tcl the channel is for binary, not textual, data so it doesn't do things like converting to an encoding like UTF-8 or on Windows do line ending conversions.

    Need

    chan configure $fp -encoding binary
    

    after you open the file. Or use set fp [open text.bin wb] instead.

    Same thing applies when opening a binary file for reading.