我想使用python 2.X
将字符串转换为二进制数Input : str = "4000ff11941859f3138e00000000673ac3b40047c0762b47818 ......"
print type(str)
>> <type 'str'>
输出应为:0100000000001111000100011001010000011000101 .......
eg: 4 as 0100
f as 1111
有人可以建议怎么做吗?提前致谢。
答案 0 :(得分:0)
我会这样做:
str = '4000ff11941859f3138e00000000673ac3b40047c0762b47818'
print(bin(int(str, 16)))
Output:
01000000000000001111111100010001100101000001100001011001111100110001001110001110000000000000000000000000000000000110011100111010110000111011010000000000010001111100000001110110001010110100011110000001100
答案 1 :(得分:0)
这是一个代码示例。
您不应将str
用作变量名称,它将覆盖内置的str()
函数。
你需要注意二进制表示的长度。
data = "a1ef4"
new_data=""
base = 16
# look at all characters in the string
for char in data:
# convert to integer
number = int(char, base)
# convert to binary and then to string
# the string has variable length
# 4 becomes 100, not 0100
binary = bin(number)
binary_string = str(binary)
# convert to string with fixed length
binary_string = '{0:04b}'.format(number)
# append to output data
new_data += binary_string
# newdata == "10100001111011110100"