0

i would like to implement XOR operation of 1000000^10100001.

def keygen(key):
    print (key)
    k0 = key
    w0 = k0[0:8]
    w1 = k0[8:]

    w2 = int(w1) ^ int(10000000)

But im not getting the correct output. My w1 is:10100001 and my binary o.p w2 is:0b100110001011110110000010.

I should get: 00100001

4
  • 1
    If you want to use the number as a bitflag, make it binary with 0b100000 Commented Mar 6, 2017 at 17:19
  • i dont want bit flag, just need to implement XOR.. Any suggestion? Commented Mar 6, 2017 at 17:21
  • 3
    Suggestion: blindly follow my comment and see what happens. Commented Mar 6, 2017 at 17:23
  • @BallpointBen, It should be 0b10000000. Commented Mar 6, 2017 at 17:39

1 Answer 1

1

You need to use 0b... to denote binary number.

Also when converting string to a number using int, specify base 2 (the second optional parameter). Otherwise it is interpreted as a decimal number:

w2 = int(w1, 2) ^ 0b10000000
#            ^    ^^------------ binary (= 128 in decimal)
#            |
#            optional argument (base 2)

And, you don't need to call int for 0b10000000, because it's already an int object.


UPDATE If you want to get a string representation back, use str.format or format with format specify 08b (0: leading zeros, 8: at least 8 digits, b: binary)

>>> format(w2, '08b')
00100001
Sign up to request clarification or add additional context in comments.

9 Comments

Thank you, it worked. One more question.. Is there a way to remove the bit flag? or do ive to convert to string and remove the 0b
@GoldyTomy, binary 0b10000000 is decimal 128. So, you can replace the line with w2 = int(w1, 2) ^ 128
my requirement is to use bits for my program, after the XOR operation i need to work with bits. Thats why i cant use 128. Moreover, if i change the input w1 to 10011010, my output becomes 0b11010, which is not eight bit output.
@GoldyTomy, I don't get what you mean. Do you want result back as a string? then try bin(w2) (this will give you a string with a prefix 0b), format(w2, 'b'), format(w2, '08b') (at least 8 string with leading 0 if needed) or '{:08b}'.format(w2), ...
so, what im looking is w2 = 10011010 ^ 10000000 and the output should also be 8 bit output in bits. the above format you gave is working but it just removes the 0 in front. Im working in a code which deals only with bits, so i guess i need to check the output and then append the missing zeros if there are any.
|

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.