Passing Binary Data Between Chilkat and Ruby

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


require 'chilkat'

bd = Chilkat::CkBinData.new()

# Create a binary string in Ruby.
binary_string = "\x00\x01\x02\x03\x04"

# Copy the bytes to the CkBinData object.
bd.AppendData(binary_string,binary_string.size)

# View the contents of bd in hexadecimal format.
# Output: 0001020304
print bd.getEncoded("hex") + "\n"

# Append a few more bytes
bd.AppendEncoded("05060708","hex")

# Call GetData to copy the bytes to a new binary string
binary_string = bd.GetData()

# Print each byte value
binary_string.each_byte { |byte| puts byte }
print "----\n"

# 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.

binary_string = bd.GetDataChunk(2,4)
binary_string.each_byte { |byte| puts byte }

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