Home >Backend Development >Python Tutorial >What are the common hexadecimal conversion methods in python?

What are the common hexadecimal conversion methods in python?

WBOY
WBOYforward
2023-05-12 14:22:2012398browse

1. Standard base conversion

The most commonly used one is Python's built-in function for base conversion. Generally, when using the built-in function for conversion, the string input from the console or The custom string is first converted to decimal and then converted to other decimals. Common conversions are binary, decimal, octal, and hexadecimal. One principle is followed:

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 with the help of Decimal is used as an intermediate bridge for conversion, that is, the int() function is used.

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

The following table reflects the conversion between common bases


Binary system Octal system Decimal system Hexadecimal system
Binary - bin(int(input(), 8)) bin(int(input(), 10)) bin(int(input(), 16))
octal oct(int(input(), 2)) - oct(int(input(), 10)) oct(int(input(), 16))
Decimal int(input(),2)) int(input(),8) - int(input (), 16)
16 hex hex(int(input(), 2)) hex(int(input() , 8)) hex(int(input(), 10)) -

When using built-in functions anyway To convert to which base system you want, just use a function corresponding to the base system. In the middle, you need to convert to decimal system (int() function). The built-in functions involved in base system conversion are: binary system: bin(), 8 Base: 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 in format b, o, x convert other bases into 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 any 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))

Other bases are converted 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__ == &#39;__main__&#39;:
    li = input().split()
    print(Solution().anyToDecimal(li[0], int(li[1])))

Supplement

10 base negative numbers are converted to binary

m = -1
bin(m & 0xffffffff)

Convert between integers

# 1. 10 -> 16
hex(number)
# 2. 10 -> 2
bin(number)
# 3. 10 -> 8
oct(number)# 4. x进制 -> 10
int(Union[str, bytes, bytearray],base=x)
------------------
print(int("0x16", base=16)) // 22

Convert string to integer

# 10进制
val = int(&#39;10&#39;)
print(type(val), val)
# 16进制
val = int(&#39;0xa&#39;, 16)
print(type(val), val)
val = int(&#39;a&#39;, 16)
print(type(val), val)
# 2进制
val = int(&#39;0b1010&#39;, 2)
print(type(val), val)
val = int(&#39;1010&#39;, 2)
print(type(val), val)
----------------------------无意义------------------------------
# 3进制
val = int(&#39;101&#39;, 3)
print(type(val), val)
# 5进制
val = int(&#39;60&#39;, 5)
print(type(val), val)

The above is the detailed content of What are the common hexadecimal conversion methods in python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete