pythonbitstring

Python: ValueError: invalid literal for int() with base 2: '1001001 1101101 ...."


My XOR accepts two bitstrings and returns the XOR value of those two strings. I don't think the getXor function is reading the bitstring as integers and I've tried making changes but I'm not certain where as none of my efforts have worked.

import random

def getCaesar(message, key):
    enc = ""
    for char in message: 
        if char == ' ':
            enc = enc + char
        elif  char.isupper():
            enc = enc + chr((ord(char)+key-65)%26+65)
        elif char.islower():
            enc = enc + chr((ord(char) + key - 97) % 26 + 97)
        else:
            enc = enc +chr((ord(char) + key - 33) % 32 + 33)

    return enc

def getBinary(bitstr):
    bit=' '.join(format(ord(char), 'b') for char in bitstr)
    return bit

def getBitstr(k):
    result=""
    for num in range(0,k):
        result=''.join(str(random.randint(0,1))for num in range(k))
    return result

def getXor(a,b):
    result = int(a,2) ^ int(b,2)
    return '{0:b}'.format(result)


f=open("NoWar.txt", mode="r")
l=f.read()

binary=getBinary(l)
a=str(binary)
size=len(binary)
key=getBitstr(size)
b=str(key)
x=getXor(a,b)


cipher=getCaesar(key,4)
cipher="".join(cipher)
cipherF=open("ciphertext.txt", mode="w")
cipherF.write(cipher)
cipherF.close()

The error calls out:

result = int(a,2) ^ int(b,2)

With the error: ValueError: invalid literal for int() with base 2: '1001001 1101101 1110000 1100101 1100001 1100011 1101000 1101101 1100101 1101110 1110100'

How do I fix this?


Solution

  • You need to remove whitespace, try a.replace(' ', '') and same for b.