Base64-encoded binary term literals
Requires Analytica 6.2
Binary data is a sequence of bytes that is generally uninterpretable to the human eye, but contains data used by a computer program. Many data file formats use custom binary formats.
Binary data can be encoded directly in an Analytica expression using a base-64 encoding]. The encoding uses only printable characters to represent the binary data in which each sequence of 6 bytes encodes as 8 printable characters. The encoding is standard and not unique to Analytica. A base64-encoded literal is starts with the prefix base64'
and ends with a matching quote ('
). Single or double quotes can be used, there is no functional difference. The following example encodes the 5 bytes [01, 02, 03, 04, 05] (all would be unprintable characters):
base64'AQIDBAU='
You can get the number of bytes in the encoded binary data using
BinaryDataSize(base64'AQIDBAU=')
→ 5
Evaluated value
When you evaluate a base64-encoded literal, the result is a binary data term. This is an in-memory sequence of bytes. The previous example displays as «BinaryData 5 bytes»
. The contents of a binary data term would usually be human unreadable, but can be accessed using the GetFromBinaryData function. For example, the following splits the previous example into a list of 5 "bytes":
GetFromBinaryData( base64'AQIDBAU=', bytesPer:1, typeFlags:0 )
The «typeFlags» option 0 specifies "unsigned integer", so this reads 1-bytes unsigned integers (i.e., bytes) from the binary data literal. The result in this example is [1, 2, 3, 4, 5]
.
Assignment
When you copy a result to a global variable using assignment (such as from a button OnClick), a binary data literal becomes a base64-encoded binary term literal in the global variable's definition.
Embedding binary data in model file
A base64-encoded binary data term makes it possible to embed binary data directly in your model, so that the data does not have to be read from a separate data file. One use case of this occurs when you want to Analytica Free edition users to have access to the binary file. The ReadBinaryFile function requires Analytica Enterprise, GetFromBinaryData works in any edition.
To embed a binary file as a base64-encoded literal, first read the entire file contents into memory using ReadBinaryFile and then from a button, copy the result into a global variable or constant that will hold the literal. That is demonstrated in this code:
- Variable TheBinaryData
- Button CopyFileToMemory
- OnClick:
TheBinaryData := ReadBinaryFile( "myDataFile.bin", typeFlags: 7 )
Enable comment auto-refresher