Bytes, math & arrays
-- Doc example: bytes, math, and numeric arrays / linear algebra (all pure).
intent: "doc example: bytes, math and arrays"
print("decode(bytes(\"Hi\")) = " + decode(bytes("Hi")) + ", norm([3,4]) = " + text(norm(array([3, 4]))))
test "bytes <-> text are inverses; hex encoding"
let b be bytes("Hi")
assert_eq(decode(b), "Hi")
assert_eq(decode(bytes("Hi"), "hex"), "4869")
assert_eq(decode(bytes("4869", "hex")), "Hi")
test "base58/base32 round-trip; bytes <-> exact integers"
assert_eq(decode(bytes(decode(bytes("Hi"), "base58"), "base58")), "Hi")
assert_eq(decode(bytes("Hi"), "base32"), "JBUQ")
-- bytes_to_int/int_to_bytes: big-endian, exact (protocol/signature integers)
assert_eq(bytes_to_int(bytes("0400", "hex")), 1024)
assert_eq(int_to_bytes(1024), bytes("0400", "hex"))
assert_eq(int_to_bytes(7, 4), bytes("00000007", "hex"))
test "math operators"
assert_eq(2 ** 10, 1024)
assert_eq(10 % 3, 1)
test "numeric arrays + linear algebra"
assert_eq(norm(array([3, 4])), 5)
assert_eq(dot(array([1, 2, 3]), array([4, 5, 6])), 32)
Bytes
bytes is raw binary, distinct from text. bytes(...) and decode(...) are inverses:
bytes("Hi") -- UTF-8 bytes
bytes("4869", "hex") -- decode hex → bytes
bytes("SGk=", "base64") -- decode base64 → bytes
bytes("SGk", "base64url") -- decode base64url (URL-safe -_, padding optional; JWT/tokens) → bytes
bytes("StV1DL6", "base58") -- decode base58 (Bitcoin/Solana alphabet) → bytes
bytes("JBSWY3DP", "base32") -- decode base32 RFC 4648 (Algorand convention) → bytes
decode(b) -- bytes → text (UTF-8 strict)
decode(b, "hex") -- bytes → hex text (also base64 / base64url / base58 / base32)
sha256(x) -- raw digest (bytes); hex via decode(sha256(x), "hex")
bytes_to_int(b) -- big-endian bytes → exact non-negative integer (empty → 0)
int_to_bytes(n, size?) -- integer → big-endian bytes: minimal, or zero-padded to size
int_to_bytes_le(n, size) -- integer → little-endian bytes of exactly size (binary structs, e.g. Solana u32/u64 LE)
text(b) shows a hex repr like bytes(48656c6c6f) — it does not decode. A secret never materializes through bytes(...). bytes_to_int is exact at any width (a 32-byte value never touches float), which is what signature/protocol integers need — see 38-blockchain.
Math
Operators + - / % ; division is always float*. Constants: pi, tau, e, inf, nan. Numeric tower also has decimal (1.50d, exact) and complex.
Numeric arrays & linear algebra
array([...]) builds a numeric array; + - / * are elementwise (with broadcasting). Linear algebra (2D, via faer):
norm(array([3, 4])) -- 5
dot(array([1, 2, 3]), array([4, 5, 6])) -- 32
matmul(a, b) -- matrix product
solve(A, b) det(A) inv(A) eig(A) svd(A)