Bytes Module
Import using: use bytes
Creation & Conversion
bytes.alloc(size)- Create byte array of given size (all zeros). O(n).bytes.fromString(str)- String to UTF-8 byte array (character ordinals).bytes.toString(byteArray)- Byte array to UTF-8 string.bytes.fromInteger(n, byteCount)- Unsigned integer to big-endian byte array.bytes.toInteger(byteArray)- Big-endian byte array to unsigned integer.bytes.bytesToHex(byteArray)- Byte array to hex string.bytes.hexToBytes(hexStr)- Hex string to byte array.
use bytes
let arr = bytes.alloc(4)
print(str(arr)) # [0, 0, 0, 0]
let str = bytes.fromString("Hi")
print(str(str)) # [72, 105]
print(bytes.toString(str)) # Hi
let hex = bytes.bytesToHex(str)
print(hex) # 4869
let back = bytes.hexToBytes(hex)
print(bytes.toString(back)) # Hi
let num = bytes.fromInteger(255, 2)
print(str(num)) # [0, 255]
print(str(bytes.toInteger(num))) # 255
Manipulation
bytes.length(byteArray)- Number of bytes.bytes.slice(byteArray, startIdx, endIdx)- Extract sub-array [start, end).bytes.copy(byteArray)- Deep copy.bytes.fill(byteArray, val)- Fill in-place with given value (0-255).bytes.concat(a, b)- Concatenate two byte arrays (mutates first).bytes.equal(a, b)- Compare by value, not by reference.
use bytes
let a = bytes.fromString("Hello")
let sliced = bytes.slice(a, 0, 3)
print(bytes.toString(sliced)) # Hel
let copy = bytes.copy(a)
print(str(bytes.equal(a, copy))) # True
bytes.fill(a, 65)
print(bytes.toString(a)) # AAAAA
let b = bytes.fromString(" World")
bytes.concat(a, b)
print(bytes.toString(a)) # Hello World