Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

math.bases

hex, binary, octal and any base 2-36; digits of a number

Example results generated on 2026-10-08. Ones using now, today or randomness will differ when you run them: press Run on any example to run it in your browser, after editing it if you like.

conversions

# to hex bin oct dec
255 to bin
# → 0b11111111
# to hex(bits), to base(b)
-1 to hex(16)
# → 0xffff

Functions

functiondescription
hex(v: int|float|str, bits?: int)same as v to hex / v to hex(bits); strings become hex bytes
bin(v: int|float, bits?: int)same as v to bin / v to bin(bits)
oct(v: int|float, bits?: int)same as v to oct
dec(v: int|float, bits?: int)same as v to dec; with bits, reads two’s complement as unsigned
base(v: int|float, b: int)same as v to base(b), any base 2-36
digits(n: int)list of digits in the number’s own base
from_digits(xs: list, base?: int)build a number from digits, kept in that base

hex

hex(v: int|float|str, bits?: int): same as v to hex / v to hex(bits); strings become hex bytes

hex(255)
# → 0xff
hex(-1, 16)
# → 0xffff
hex("hi")
# → "6869"

See also: bin, base, int

bin

bin(v: int|float, bits?: int): same as v to bin / v to bin(bits)

bin(10)
# → 0b1010
bin(5, 8)
# → 0b00000101

See also: hex, oct

oct

oct(v: int|float, bits?: int): same as v to oct

oct(8)
# → 0o10

See also: hex, bin

dec

dec(v: int|float, bits?: int): same as v to dec; with bits, reads two’s complement as unsigned

dec(0xff)
# → 255
dec(-1, 8)
# → 255

See also: hex, int

base

base(v: int|float, b: int): same as v to base(b), any base 2-36

base(35, 36)
# → 36#z
base(10, 3)
# → 3#101

See also: hex, digits

digits

digits(n: int): list of digits in the number’s own base

1234.digits
# → [1, 2, 3, 4]
0b1011.digits
# → [1, 0, 1, 1]

See also: from_digits

from_digits

from_digits(xs: list, base?: int): build a number from digits, kept in that base

[1, 2, 3].from_digits
# → 123
[1, 0, 1, 1].from_digits(2)
# → 0b1011

See also: digits

More examples

bases

# number bases
255 to bin
# → 0b11111111
# any base back to decimal
36#zz to dec
# → 1295
# hex of a big int
factorial(20) to hex
# → 0x21c3677c82b40000
# results keep their base
0xff + 1
# → 0x100
# two's complement
-1 to hex(16)
# → 0xffff
# base 36
255 to base(36)
# → 36#73
# digit sum
(2 ** 100).digits.sum
# → 115