Reputation: 385
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
Upvotes: 0
Views: 119
Reputation: 28596
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
Upvotes: 2