News from this site

 Rental advertising space, please contact the webmaster if you need cooperation


+focus
focused

classification  

no classification

tag  

no tag

date  

2024-11(8)

python常见进制转换方法

posted on 2023-05-21 18:04     read(560)     comment(0)     like(11)     collect(4)


1. Standard conversion

Among them, the built-in function of python is more commonly used for base conversion. Generally, when using the built-in function for conversion, the string input by the console or the custom string is first converted to base 10 and then the base 10 is converted. Conversion from binary system to other base systems, common conversions between binary, decimal, octal, and hexadecimal, one of which follows a principle:

Use the int function to convert other bases to decimal, use the bin function to convert other bases to binary, use the oct function to convert other bases to octal, and use the hex function to convert other bases to hexadecimal, and use the decimal Make it as an intermediate bridge for conversion, that is, use the int() function.

And after converting to the corresponding weight, the corresponding string will have a corresponding prefix, the binary prefix is ​​0b, the octal prefix is ​​0o, and the hexadecimal prefix is ​​0x

The table below reflects conversions between common bases

Binaryoctal10 hexHexadecimal
Binary-bin(int(input(),8))bin(int(input(),10))bin(int(input(),16))
octaloct(int(input(), 2))-oct(int(input(),10))oct(int(input(),16))
10 hexint(input(),2))int(input(),8)-int(input(),16)
Hexadecimalhex(int(input(), 2))hex(int(input(),8))hex(int(input(),10))-

When using the built-in function, you can use a function corresponding to the base to convert to. In the middle, you need to convert to decimal first (int() function), and the built-in functions involved in the base conversion are: 2 base System: bin(), octal: oct(), decimal: int(), hexadecimal: hex()

if __name__ == '__main__':
    # input接收到的是字符串, 使用int函数定义输入的是什么进制的字符串转换为10进制数字
    print(bin(int(input(), 16)))
    print(int(input(), 10))
    print(oct(int(input(), 10)))
    print(hex(int(input(), 10)))

format function for conversion
Add b, o, x to format to convert other bases to binary, octal or hexadecimal

if __name__ == '__main__':
    print("{:b}".format(int(input(), 8)))
    print("{:o}".format(int(input(), 8)))
    print("{:x}".format(int(input(), 8)))

2. Conversion between arbitrary bases

Convert decimal to other base codes

class Solution:
    # 将十进制数字转换为任意的进制(1-16)
    def decimalToAny(self, decimal: int, x: int):
        remainder = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
        # 当n大于0的时候执行循环
        res = ""
        while decimal:
            res = remainder[decimal % x] + res
            decimal //= x
        return res
 
if __name__ == '__main__':
    decimal, x = map(int, input().split())
    print(Solution().decimalToAny(decimal, x))

Convert other bases to 10

class Solution:
    # 快速幂: x ** n
    def quickPower(self, x: int, n: int):
        res = 1
        while n > 0:
            if n % 2 == 1:
                res *= x
            x *= x
            n //= 2
        return res
 
    def anyToDecimal(self, s: str, base: int):
        n = len(s)
        res = 0
        for i in range(n):
            # 数字, ord函数获取字母的ascii值
            if "0" <= s[i] <= "9":
                res += (ord(s[i]) - ord("0")) * self.quickPower(base, n - i - 1)
            # 16进制数字对应的权重
            elif "a" <= s[i] <= "f":
                res += (ord(s[i]) - ord("a") + 10) * self.quickPower(base, n - i - 1)
            else:
                res += (ord(s[i]) - ord("A") + 10) * self.quickPower(base, n - i - 1)
        return res
 
if __name__ == '__main__':
    li = input().split()
    print(Solution().anyToDecimal(li[0], int(li[1])))

Replenish

Decimal negative numbers converted to binary

m = -1
bin(m & 0xffffffff)


Category of website: technical article > Blog

Author:gfg

link:http://www.pythonblackhole.com/blog/article/25323/eb3ce077b70604e01e6e/

source:python black hole net

Please indicate the source for any form of reprinting. If any infringement is discovered, it will be held legally responsible.

11 0
collect article
collected

Comment content: (supports up to 255 characters)