How Do I Process a Binary File?
This lesson will show you how to open a binary file, process binary data and write binary data to a file.
Reading a Binary File Into LiveCode
When loading data into LiveCode from a file you have two options - load the data as text or load the data as binary. Loading file data as binary means that the LiveCode engine will load the data as-is, without converting any line feeds or return characters. The same holds true when writing a file to disk as well.
You can choose one of two methods for loading the data.
1) Use the commands open file, read from file and close file.
put "/path/to/myimage.png" into theFilePath
open file theFilepath for binary read
read from file theFilePath until end
put it into theBinaryData
close file theFilePath
2) Use the URL keyword with the put command, prefixing the file path with "binfile:".
put "/path/to/myimage.png" into theFilePath
put URL ("binfile:" & theFilePath) into theBinaryData
Either approach allows you to place binary data into a variable so that it can be processed.
Accessing Bytes In Binary Data
With LiveCode you can access individual bytes in binary data by using the byte chunk. For example, if I want to access byte 8 in some binary data I could do the following:
## Assume that binary data is stored in the variable theBinaryData
put byte 8 of theBinaryData into theByte
## Loop through all bytes in data
repeat for each byte theByte in theBinaryData
-- process theByte here (but don't modify directly)
end repeat
Decoding Binary Data
LiveCode also allows you to decode binary data into various formats using the binaryDecode function. For example, if you wanted to decode the 8-byte signature of PNG data into hexadecimal digits you could do the following:
## Assume the variable thePNGData already has PNG data stored in it.
## Convert first 8 bytes to hexadecimal digits
put binarydecode("H16", thePNGData, theSignature) into theNumConversions
## The variable theSignature now contains '89504e470d0a1a0a' if theSignature contains valid data.
put theSignature
Writing a Binary File From LiveCode
Writing data from LiveCode to a file is the same as loading the data - you must explicitly tell the LiveCode engine that you want to write the data as binary data.
You can choose one of two methods for writing the data.
1) Use the commands open file, write to file and close file.
put "/path/to/myimage.png" into theFilePath
open file theFilepath for binary write ## you might also use 'binary update' here to modify part of file
write theBinaryData to file theFilePath
close file theFilePath
2) Use the URL keyword with the put command, prefixing the file path with "binfile:".
put "/path/to/myimage.png" into theFilePath
put theBinaryData into URL ("binfile:" & theFilePath)
Either approach allows you to write binary data to a file. One difference to be aware of is that open file allows you the option of updating part of a file while the put form does not.
0 Comments
Add your comment