Passing Binary Data Between Chilkat and TCL

This example explains how to pass binary data between Chilkat and TCL.



load /Users/joe/tcl_test/chilkat.dylib

set bd [new_CkBinData]

# Create a binary string in TCL.
set binary_string [binary format c* {0 1 2 3 4}]

# Copy the bytes to the CkBinData object.
set success [CkBinData_AppendData $bd $binary_string [string length $binary_string]]

# View the contents of bd in hexadecimal format.
# Output: 0001020304
puts [CkBinData_getEncoded $bd "hex"]

# Append a few more bytes
set success [CkBinData_AppendEncoded $bd "05060708" "hex"]

# Call GetData to copy the bytes to a new binary string
set binary_string [CkBinData_GetData $bd]

# Print each byte value
set length [string length $binary_string]
for {set i 0} {$i < $length} {incr i} {
    binary scan $binary_string @${i}c byte
    puts "Byte $i: $byte"
}
puts "----"

# Output is:
# 0
# 1
# 2
# ...
# 8
    
# You can get a range of bytes by calling GetDataChunk
# GetDataChunk has 0-based indexing.  The 1st byte is at index 0.

set binary_string [CkBinData_GetDataChunk $bd 2 4]
set length [string length $binary_string]
for {set i 0} {$i < $length} {incr i} {
    binary scan $binary_string @${i}c byte
    puts "Byte $i: $byte"
}

# Output is:
# 2
# 3
# 4
# 5