HighARc
HighARc

Reputation: 117

Special Chars not converting in to binary well in python

I am working an a XOR encryption model in Python and thus far everything works great except for numbers, and punctuation.

Any number or punctuation will give you a invalid binary string however, any basic letters at least in the english alphabet work.

What am I doing wrong here? I have traced it down to this method:

def IMpassEnc(self,password):
    binaryList = ""
    for i in password:
        if i == " ":
            binaryList += "00100000"  #adding binary for space
        else:
            tmp = bin(int(binascii.hexlify(i),16)) #Binary Conversion
            newtemp = tmp.replace('b','')  
            binaryList += newtemp
    return binaryList

Upvotes: 0

Views: 262

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124110

You need to generate binary representations that are 8 bits wide; bin() does not give you that.

The better way to produce these results is to use format(value, '08b'); this produces 8-character wide binary representations, padded with 0. Moreover; ord() would be a much more direct way to get the integer codepoint for a given character:

>>> format(ord(' '), '08b')
'00100000'
>>> format(ord('a'), '08b')
'01100001'
>>> format(ord('!'), '08b')
'00100001'

or, put together using ''.join():

def IMpassEnc(self, password):
    return ''.join(format(ord(c), '08b') for c in password)

Upvotes: 2

Related Questions