0

lets say i have the following variable data=0xab12cd30 i would like to get the xor over the 32 bits (for example in verilog ^data)

for example (giving 8bit examples)

data = 0x11 -> result should be 0

data = 0x10 -> result shoule be 1

data = 0x21 -> result should be 0

data = 0x23 -> result should be 1

What is the easiest way? Using Python 2.4.3

1
  • you want xor by what? Commented Jun 3, 2015 at 20:33

1 Answer 1

2

Easiest? Maybe this:

bin(data).count('1') % 2

Demo:

>>> for data in 0x11, 0x10, 0x21, 0x23:
        print bin(data).count('1') % 2

0
1
0
1

Edit: If using an awfully old Python that doesn't have bin, here's a do-it-yourself solution:

for data in 0x11, 0x10, 0x21, 0x23:
    xor = 0
    while data:
        xor ^= data & 1
        data >>= 1
    print xor

Edit 2: A faster and more tricky solution:

for data in 0x11, 0x10, 0x21, 0x23:
xor = 0
while data:
    xor ^= 1
    data &= data - 1      # deletes the last 1-bit
print xor
Sign up to request clarification or add additional context in comments.

3 Comments

Hmm, i dont have the bin method (Version 2.4.3)... i dont mind to iterate over each bit, by how do i do it?
@Jonathan Ugh... nobody should still be using such an old version :-). But ok, I added another solution to my answer.
@Jonathan And now I added another, less easy but faster and more interesting one.

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.