mp.utils — 43 functions
Hex ↔ bytes
| Function | Returns | Description |
|---|---|---|
hex_to_bytes(hex) | table | "4865" → {0x48, 0x65} |
bytes_to_hex(bytes) | string | {0x48, 0x65} → "4865" |
bytes_to_string(bytes) | string | Byte array → raw string |
string_to_bytes(s) | table | Raw string → byte array |
is_ascii(bytes) | bool | All bytes are printable ASCII (0x20..0x7E) |
is_printable(bytes) | bool | Printable + \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) | number | Parse hex string (up to 64-bit) |
Byte order
| Function | Returns | Description |
|---|---|---|
swap16(v) | int | Endian swap 16-bit |
swap32(v) | number | Endian swap 32-bit |
le16(lo, hi) | int | Assemble little-endian 16-bit |
be16(hi, lo) | int | Assemble big-endian 16-bit |
le32(b0, b1, b2, b3) | number | Assemble LE 32-bit (b0 = LSB) |
be32(b0, b1, b2, b3) | number | Assemble BE 32-bit (b0 = MSB) |
Bit operations (beyond Lua 5.5 native)
| Function | Returns | Description |
|---|---|---|
bit_set(v, bit) | int | Set bit |
bit_clear(v, bit) | int | Clear bit |
bit_test(v, bit) | bool | Test bit |
bit_toggle(v, bit) | int | Toggle bit |
extract_bits(v, startBit, count) | int | Extract bit field |
Time
| Function | Returns | Description |
|---|---|---|
timer() | table | {elapsed_ms(), elapsed_s(), restart()} |
timestamp() | number | ms since Unix epoch |
datetime() | string | "yyyy-MM-dd HH:mm:ss" |
date() | string | "yyyy-MM-dd" |
time() | string | "HH:mm:ss" |
JSON
| Function | Returns | Description |
|---|---|---|
json_parse(s) | table | nil | Parse JSON object/array; nil on error |
json_encode(obj) | string | Indented JSON. Empty Lua tables encode as [] (JSON array). To force an empty JSON OBJECT, pass {__json_object = true} |
json_encode_compact(obj) | string | Single-line JSON, same accepted types and same empty-table semantics |
String helpers
| Function | Returns | Description |
|---|---|---|
trim(s) | string | Strip leading/trailing whitespace |
split(s, sep) | table | Split 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) | string | Replace all occurrences |
Table helpers
| Function | Returns | Description |
|---|---|---|
table_keys(t) | table | Array of keys |
table_values(t) | table | Array of values |
table_size(t) | int | Total 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"