std.convert
std.convert
std.convert handles number/string/base conversion and printf-style
formatting.
Reference
to_hex(n) from_hex(str)
to_bin(n) from_bin(str)
to_oct(n) from_oct(str)
parse_int(str[, base]) # auto-detects 0x, 0b, 0o prefixes
format(value, fmt) # printf-style; only one conversion allowed
| Function | Description |
|---|---|
to_hex(n) / from_hex(s) |
Integer ↔ lowercase hex string |
to_bin(n) / from_bin(s) |
Integer ↔ binary string |
to_oct(n) / from_oct(s) |
Integer ↔ octal string |
parse_int(s[, base]) |
Parse an integer string to a long; base defaults to 10, infers 0x/0b/0o when omitted (prefixes override an explicit base); base must be 2–36 |
format(v, fmt) |
printf-style formatting — only one conversion specifier per call |
Examples
print(std.convert.to_hex(255)) # ff
print(std.convert.from_hex("ff")) # 255
print(std.convert.to_bin(10)) # 1010
print(std.convert.from_bin("1010")) # 10
print(std.convert.to_oct(8)) # 10
print(std.convert.parse_int("ff", 16)) # 255
print(std.convert.parse_int("0x1F")) # 31 (prefix-inferred)
print(std.convert.parse_int("0b1010")) # 10
Parsing is strict: no surrounding whitespace, no `+`/`-` signs — the whole
string must be digits in the base.
print(std.convert.parse_int("0o17")) # 15
print(std.convert.format(3.14159, "%.2f")) # 3.14
print(std.convert.format(42, "%04d")) # 0042
print(std.convert.format(255, "%x")) # ff
format accepts a single printf conversion (e.g. %d, %x, %.2f,
%04d). Pass the value and the format string — it returns the formatted
string.
See also
- std.hash — hashing digests
- std.string —
split/joinand classification helpers