0
 l = [10,11,12,13,14,15,16,17]
 bstr = b'fedora'
 to_xor = bstr[0]  

How would I XOR the 8 bits of to_xor with the 8 values in the list in an efficient manner?

i.e. the binary value of to_xor,'f', is 102: 1100110.

I would like to XOR the first bit of 'f' with the LSB of 10, second bit with the LSB of 11, third bit with LSB of 12, and so on.

1 ^ LSB of 10
1 ^ LSB of 11
0 ^ LSB of 12

This post gives some tips on converting bytes to bits, but not on XOR-ing by individual bits.

2
  • The LSBs of 10,11,12,13,14 etc are 0,1,0,1,0 and so on. Is that really what you meant? Of course if you XOR any value with zero, it will be unchanged Commented Mar 5, 2022 at 19:43
  • Yeah that is the goal. If the particular bit in the letter 'f' is 0, then yes it is fine if the corresponding number in the array is unchanged. Commented Mar 5, 2022 at 19:57

1 Answer 1

1

If you want to XOR every bit of bstr[0] with the LSB of the corresponding integer in l,

[((bstr[0] >> i) & 1) ^ (l[i] & 1) for i in range(8)]

(bstr[0] >> i) & 1) extracts the ith bit of bstr[0], (l[i] & 1) extracts the LSB of the integer l[i], and we know there are 8 bits in a byte, hence the range(8).

What you want seems to be the inverse of this (first integer in l XORs the MSB in bstr[0]), so if the solution above is inverted, try

_l = l[::-1]
XORs = [((bstr[0] >> i) & 1) ^ (_l[i] & 1) for i in range(8)][::-1]
Sign up to request clarification or add additional context in comments.

3 Comments

Neat, but it appears this XOR's each letter in the bstr with its respective number in the list. However, I just want to XOR the bits of the first letter, 'f', or bstr[0]
@Cheetaiean I've edit my answer
Thanks that is the rough idea. [((bstr[0] >> i) & 1) ^ (l[i] ) for i in range(8)]. However it appears to be in reversed order (it's XOR'ing bstr[0] from right to left instead of left to right, so processing 0110011 instead of 1100110 ). I can compensate for that though, just scan the list from right to left too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.