|
发表于 2021-10-10 14:25:58
|
显示全部楼层
本楼为最佳答案
这是我以前编写的代码,希望对你有帮助- class NumeralSystem:
- def __init__(self, num):
- self.num = num
-
- def binary(self): # 二进制
- res = []
- n = self.num
- while n > 1:
- n, b = divmod(n, 2)
- res.append(str(b))
- res.append(str(n))
- return '0b'+''.join(res[::-1])
-
- def octal(self): # 八进制
- res = []
- n = self.num
- while n > 7:
- n, b = divmod(n, 8)
- res.append(str(b))
- res.append(str(n))
- return '0o'+''.join(res[::-1])
-
- def hexadecimal(self): # 十六进制
- Hex = {10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F'}
- res = []
- n = self.num
- while n > 15:
- n, b = divmod(n, 16)
- if b > 9: res.append(Hex[b])
- else: res.append(str(b))
- if n > 9: res.append(Hex[n])
- else: res.append(str(n))
- return '0x'+''.join(res[::-1])
- num = NumeralSystem(796)
- print(num.binary())
- print(num.octal())
- print(num.hexadecimal())
复制代码- 0b1100011100
- 0o1434
- 0x31C
复制代码 |
|