0

I am starting to work on a Vernam cipher in Python and apparently there is something I do not know about working with binary in Python, for exmple if I print 00011 in console it returns a 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

Output

[65, 10000, 9, 584, 585]

I want to print the actual binary numbers insted of the ASCII version.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
etsous
  • 27
  • 6

2 Answers2

1

You need to prefix your binary numbers with 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

This outputs:

>>> 
[5, 16, 3, 14, 15]

The details for why the 0b is necessary can be found here: https://docs.python.org/2.7/reference/lexical_analysis.html#integer-and-long-integer-literals

Addenda to answer the later edit to the question:

If you want for format your output in binary, either use bin() or format():

>>> [format(e, '05b') for e in m]
['00101', '10000', '00011', '01110', '01111']
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
0

In Python, you can use different prefixes on numbers to specify different number bases.

  • If the number starts with 0b, you get a binary number (base 2). So, 0b101 == 5.
  • If the number starts with 0o (or just 0 in Python 2), you get an octal number (base 8). So 0o101 == 65.
  • If the number starts with 0x, you get a hexadecimal number (base 16). So 0x101 == 257.
  • Otherwise, you get a decimal number.
nneonneo
  • 171,345
  • 36
  • 312
  • 383