Handling Hex and Binary Data

Lua scripts often encounter hex or binary data coming from remote devices. Handling this data effectively is achieved by planning the context of how the data is formatted, which avoids inconsistencies and confusion.

Received data from the TCPSocket, UDPSocket, and Serial objects is formatted as ASCII characters and wrapped in a string. The data is stored sequentially as received and each character represents one byte (0-255 decimal).

A byte value encoded as a character in a string can be input as a hex-encoded escape character, a decimal value escape character, a character, or encoded from a number using the string.char function:

“\x41” == “\65” == ”A” = string.char(65) == string.char(0x41)

The same byte can be encoded as a number using hex notation or decimal notation, translated from a character to a numerical byte:

0x41 == 65 == string.byte(“A”)

Translating this byte data into a readable format (strings or numbers) is a common task. This allows the non-printable characters in the string of bytes to be used more effectively. The following helper functions support these tasks.

This encode/decode string function uses gsub to replace byte values with the %20X format of the value the character represents. This is a 2 digit capital letter (00-FF) representation of the value. tonumber() is used to decode this as a base 16 number back into a single character encoded value.

Casting these bytes of data into Lua numbers allows the use of bitwise operators:

Single bytes can be translated using string.char and string.byte functions. For multiple byte values, num2hex() and hex2num() translation supports up to 7 bytes.

These conversions can be changed within the helper functions if the needed translation differs from those implemented here.

Within Q-SYS designs, the input boxes encode the user’s input with escape characters. If the intended use of a text box in a text control, control script, or plugin is to receive the encoded character, the following decode script will encode the escape sequences into the appropriate character. The supported characters of this script are the c-escape strings generally supported by Lua: \x?? hex, \### decimal, \a, \b, \f, \r, \n, \t, \v.

Note: Command Buttons already support hex encoding, as documented here.