convert a number or string to binary number in python?(在python中将数字或字符串转换为二进制数?)

sample input:
B15
sample output:
B15 in binary = 1011000010101

I’ve tried

a = input()
print(bin(a))

Solution:

The hexadecimal number 0xB15 = 2837 has the binary representation 0b101100010101. So if your input is a hexadecimal number, you need to tell Python to convert the string “B15” which comes out of input() into the hexadecimal number 0xB15, also known as the decimal number 2837, before you can convert it into binary for output.

BASE = 16
a = int(input(), BASE)
print(bin(a)[2:]) # Cut of the first two characters '0b'
————————

示例输入:
B15
样本输出:
二进制B15=101100001011

我试过了

a = input()
print(bin(a))

解决方法:

十六进制数0xB15=2837具有二进制表示法0b101100010101。因此,如果您的输入是十六进制数,您需要告诉Python将input()中的字符串“B15”转换为十六进制数0xB15,也称为十进制数2837,然后才能将其转换为二进制输出。

BASE = 16
a = int(input(), BASE)
print(bin(a)[2:]) # Cut of the first two characters '0b'