7

I can't quite find a solution for this.

Basically what I've done so far is created a string which represents the binary version of x amount of characters padded to show all 8 bits.

E.g. if x = 2 then I have 0101100110010001 so 8 digits in total. Now I have 2 strings of the same length which I want to XOR together, but python keeps thinking it's a string instead of binary. If I use bin() then it throws a wobbly thinking it's a string which it is. So if I cast to an int it then removes the leading 0's.

So I've already got the binary representation of what I'm after, I just need to let python know it's binary, any suggestions?

The current function I'm using to create my binary string is here

for i in origAsci:
    origBin = origBin + '{0:08b}'.format(i)

Thanks in advance!

3
  • 1
    Why can't you just xor the ints together, then pad zeros on the left Commented Nov 21, 2016 at 16:18
  • >>> bin(22929) prints '0b101100110010001', you need 0b in front of it Commented Nov 21, 2016 at 16:22
  • get an int from a bitstring do int('010101010', 2) Commented Nov 21, 2016 at 16:33

1 Answer 1

13

Use Python's int() function to convert the string to an integer. Use 2 for the base parameter since binary uses base 2:

binary_str = '10010110' # Binary string
num = int(binary_str, 2)
# Output: 150

Next, use the bin() function to convert the integer to binary:

binary_num = bin(num)
# Output: 0b10010110
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.