Skip to main content

mp.utils — 43 functions

Hex ↔ bytes

FunctionReturnsDescription
hex_to_bytes(hex)table"4865"{0x48, 0x65}
bytes_to_hex(bytes)string{0x48, 0x65}"4865"
bytes_to_string(bytes)stringByte array → raw string
string_to_bytes(s)tableRaw string → byte array
is_ascii(bytes)boolAll bytes are printable ASCII (0x20..0x7E)
is_printable(bytes)boolPrintable + \t \n \r
byte_to_hex(b)string"AB" (2 chars)
word_to_hex(w)string"ABCD" (4 chars)
dword_to_hex(d)string"DEADBEEF" (8 chars)
hex_to_int(hex)numberParse hex string (up to 64-bit)

Byte order

FunctionReturnsDescription
swap16(v)intEndian swap 16-bit
swap32(v)numberEndian swap 32-bit
le16(lo, hi)intAssemble little-endian 16-bit
be16(hi, lo)intAssemble big-endian 16-bit
le32(b0, b1, b2, b3)numberAssemble LE 32-bit (b0 = LSB)
be32(b0, b1, b2, b3)numberAssemble BE 32-bit (b0 = MSB)

Bit operations (beyond Lua 5.5 native)

FunctionReturnsDescription
bit_set(v, bit)intSet bit
bit_clear(v, bit)intClear bit
bit_test(v, bit)boolTest bit
bit_toggle(v, bit)intToggle bit
extract_bits(v, startBit, count)intExtract bit field

Time

FunctionReturnsDescription
timer()table{elapsed_ms(), elapsed_s(), restart()}
timestamp()numberms since Unix epoch
datetime()string"yyyy-MM-dd HH:mm:ss"
date()string"yyyy-MM-dd"
time()string"HH:mm:ss"

JSON

FunctionReturnsDescription
json_parse(s)table | nilParse JSON object/array; nil on error
json_encode(obj)stringIndented JSON. Empty Lua tables encode as [] (JSON array). To force an empty JSON OBJECT, pass {__json_object = true}
json_encode_compact(obj)stringSingle-line JSON, same accepted types and same empty-table semantics

String helpers

FunctionReturnsDescription
trim(s)stringStrip leading/trailing whitespace
split(s, sep)tableSplit into parts
starts_with(s, prefix)bool
ends_with(s, suffix)bool
contains(s, sub)bool
to_upper(s)string
to_lower(s)string
replace(s, from, to)stringReplace all occurrences

Table helpers

FunctionReturnsDescription
table_keys(t)tableArray of keys
table_values(t)tableArray of values
table_size(t)intTotal entries (counts non-integer keys too)

Examples

mp.utils.hex_to_bytes("4865") -- {0x48, 0x65}
mp.utils.bytes_to_string({72, 101}) -- "He"
mp.utils.is_ascii({0x48, 0x65}) -- true
mp.utils.le32(0x78, 0x56, 0x34, 0x12) -- 0x12345678

local cfg = mp.utils.json_parse('{"target":"STM32F1"}')
local s = mp.utils.json_encode({a = 1, b = "x"})

local t = mp.utils.timer()
mp.sleep(100)
mp.log.info("elapsed: " .. t:elapsed_ms() .. " ms")

mp.log.info(mp.utils.datetime()) -- "2026-05-08 14:30:00"