Passing Binary Data Between Chilkat and Python

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

import chilkat2

bd = chilkat2.BinData()

# Create a memoryview in Python.
data = bytes([0, 1, 2, 3, 4])  # Immutable bytes object
view = memoryview(data)

# Copy the bytes in the memoryview to the CkBinData object.
bd.AppendData(view,len(view))

# View the contents of bd in hexadecimal format.
# Output: 0001020304
print(bd.GetEncoded("hex"))

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

# Call GetData to copy the bytes to a new memoryview
view2 = bd.GetData()

# Print each byte value
for byte in view2:
    print(byte)
print("----")

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

view3 = bd.GetDataChunk(2,4)
for byte in view3:
    print(byte)

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