🛠️ToolsShed

Number Base Converter

在二进制、八进制、十进制和十六进制之间转换数字。

十进制(Base 10)
二进制(Base 2)
八进制(Base 8)
十六进制(Base 16)

数制转换器在计算机中最常遇到的四种数制之间转换整数值:十进制(base 10)、二进制(base 2)、八进制(base 8)和十六进制(base 16)。每种系统使用不同的数字集表示相同的值,并在特定上下文中使用——硬件中使用二进制,内存地址和颜色代码中使用十六进制,日常算术中使用十进制。

在四个字段中的任一字段中输入数字,工具会立即填写其他三个。二进制输出以半字节(4 位)分组以提高可读性,十六进制输出以大写显示。

理解进制转换对于读取 RGB 颜色代码、解释 Unix 文件权限、处理位运算以及读取内存转储或反汇编代码至关重要。

常见问题

代码实现

# Python: built-in base conversion

# Decimal → other bases
n = 255
print(bin(n))   # '0b11111111'   (binary)
print(oct(n))   # '0o377'        (octal)
print(hex(n))   # '0xff'         (hex)

# Other bases → decimal using int(string, base)
print(int("ff", 16))        # 255  (hex → decimal)
print(int("11111111", 2))   # 255  (binary → decimal)
print(int("377", 8))        # 255  (octal → decimal)

# Arbitrary base → decimal (base 36 example)
print(int("z", 36))         # 35

# Decimal → arbitrary base string
def to_base(n: int, base: int) -> str:
    digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    if n == 0:
        return "0"
    result = []
    while n:
        result.append(digits[n % base])
        n //= base
    return "".join(reversed(result))

print(to_base(255, 16))   # FF
print(to_base(255, 2))    # 11111111

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.