Reputation: 235
So I am trying to convert a string to binary then xor the binary by using the following methods
def string_to_binary(s):
return ' '.join(map(bin,bytearray(s,encoding='utf-8')))
def xor_bin(a,b):
return int(a,2) ^ int(b,2)
When I try and run the xor_bin
function I get the following error:
Exception has occurred: exceptions.ValueError
invalid literal for int() with base 2: '0b1100010 0b1111001 0b1100101 0b1100101 0b1100101'
I can't see what's wrong here.
Upvotes: 1
Views: 539
Reputation: 123463
Your question is unclear because you don't show how the two functions you defined where being used when the error occurred — therefore this answer is a guess.
You can convert a binary string representation of an integer into a Python int
, (which are stored internally as binary values) by simply using passing it to the int()
function — as you're doing in the xor_bin()
function. Once you have two int
values, you can xor them "in binary" by simply using the ^
operator — which again, you seem to know.
This means means to xor the binary string representations of two integers and convert the result back into a binary string representation could be done like this you one of your functions just as it is. Here's what I mean:
def xor_bin(a, b):
return int(a, 2) ^ int(b, 2)
s1 = '0b11000101111001110010111001011100101'
s2 = '0b00000000000000000000000000001111111'
# ---------------------------------------
# '0b11000101111001110010111001010011010' expected result of xoring them
result = xor_bin(s1, s2)
print bin(result) # -> 0b11000101111001110010111001010011010
Upvotes: 0
Reputation: 155418
bin
is bad here; it doesn't pad out to eight digits (so you'll lose data alignment whenever the high bit is a 0
and misinterpret all bits to the left of that loss as being lower magnitude than they should be), and it adds a 0b
prefix that you don't want. str.format
can fix both issues, by zero padding and omitting the 0b
prefix (I also removed the space in the joiner string, since you don't want spaces in the result):
def string_to_binary(s):
return ''.join(map('{:08b}'.format, bytearray(s, encoding='utf-8')))
With that, string_to_binary('byeee')
gets you '0110001001111001011001010110010101100101'
which is what you want, as opposed to '0b1100010 0b1111001 0b1100101 0b1100101 0b1100101'
which is obviously not a (single) valid base-2 integer.
Upvotes: 2