如何打印二进制数

时间:2015-05-23 05:29:24

标签: python python-2.7 binary

我开始研究Python中的Vernam密码,显然我不知道在Python中使用二进制文件,例如,如果我在控制台中print 00011返回9

"""Sistema de Cifrado Vernam"""


#alfabeto
alfabeto = {"a":00011,"b":11001,"c":01110,"d":01001,"e":00001,"f":01101,"g":11010,"h":10100,"i":00110,"j":01011,"k":01111,"l":10010,"m":11100,
            "n":01100,"o":11000,"q":10111,"r":01010,"s":00101,"t":10000,"u":00111,"v":11110,"w":10011,"x":11101,"y":10101,"z":10001,
            "<":01000,"=":00010,"fdown":11111,"fup":11011," ":00100, "":00000}

"""Mensaje en texto plano"""
#Susituir por input
mensaje = "stack"
m = []
for e in mensaje:
    m.append(alfabeto[e])
print m

输出

[65, 10000, 9, 584, 585]

我想打印ASCII版本的实际二进制数。

2 个答案:

答案 0 :(得分:1)

您需要在二进制数字前加var serviceURL = "http://admin:pass@xyz.abc.def";

0b

输出:

"""Sistema de Cifrado Vernam"""

#alfabeto
alfabeto = {"a":0b00011,"b":0b11001,"c":0b01110,"d":0b01001,"e":0b00001,"f":0b01101,"g":0b11010,"h":0b10100,"i":0b00110,"j":0b01011,"k":0b01111,"l":0b10010,"m":0b11100,
            "n":0b01100,"o":0b11000,"q":0b10111,"r":0b01010,"s":0b00101,"t":0b10000,"u":0b00111,"v":0b11110,"w":0b10011,"x":0b11101,"y":0b10101,"z":0b10001,
            "<":0b01000,"=":0b00010,"fdown":0b11111,"fup":0b11011," ":0b00100, "":0b00000}

"""Mensaje en texto plano"""
#Susituir por input
mensaje = "stack"
m = []
for e in mensaje:
    m.append(alfabeto[e])
print m

有关>>> [5, 16, 3, 14, 15] 所需原因的详细信息,请访问:https://docs.python.org/2.7/reference/lexical_analysis.html#integer-and-long-integer-literals

附录以回答稍后编辑的问题:

如果您想以二进制格式输出格式,请使用bin()format()

0b

答案 1 :(得分:0)

在Python中,您可以在数字上使用不同的前缀来指定不同的数字基础。

  • 如果号码以0b开头,则会得到二进制数字(基数为2)。所以,0b101 == 5
  • 如果数字以0o(或Python 2中的0)开头,则会得到一个 八进制数(基数为8)。所以0o101 == 65
  • 如果号码以0x开头,则会得到一个十六进制数字(基数为16)。所以 0x101 == 257
  • 否则,您会得到一个十进制数字。