I'm trying to elementwise & and elementwise | 2 lists of 8 lists of 6 binary digits, and it is working very oddly. c1 and c2 start as tuples of length 8 with elements that are tuples of length 6, and res starts out as a list version of c1.
anding:
for x in range(8):
for y in range(6):
res[x][y] = (c1[:][x][y])*(c2[:][x][y])
oring:
for x in range(8):
for y in range(6):
res[x][y] = int(c1[:][x][y] or c2[:][x][y])
An example:
c1: ((1, 0, 0, 0, 1, 1), (1, 1, 0, 0, 0, 1), (1, 1, 1, 0, 0, 0), (0, 1, 1, 1, 1, 0), (1, 0, 0, 0, 1, 1), (0, 1, 1, 0, 0, 0), (1, 1, 0, 1, 0, 0), (0, 1, 0, 0, 1, 0))
c2: ((1, 0, 1, 1, 0, 0), (0, 1, 0, 1, 1, 0), (0, 1, 1, 0, 1, 0), (0, 0, 0, 0, 1, 1), (1, 1, 0, 0, 1, 0), (1, 0, 1, 0, 1, 0), (0, 0, 0, 1, 0, 1), (0, 0, 1, 0, 1, 0))
anding res:[[1, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0], [1, 0, 0, 0, 1, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0]]
oring res: [[1, 1, 0, 0, 1, 1], [1, 1, 0, 1, 1, 1], [1, 1, 1, 0, 1, 0], [0, 1, 1, 1, 1, 1], [1, 1, 0, 0, 1, 1], [1, 1, 1, 0, 1, 0], [1, 1, 0, 1, 0, 1], [0, 1, 1, 0, 1, 0]]
Other inputs for c1 and can be messed up in much more than the first sublist.
Edit: This has been resolved. It was most likely alias issues in other parts of the code, and I just ended up using list comprehensions.
In Python, bitwise operators are used to performing bitwise calculations on integers. The integers are first converted into binary and then operations are performed on bit by bit, hence the name bitwise operators.
They are bit shift operator which exists in many mainstream programming languages, << is the left shift and >> is the right shift, they can be demonstrated as the following table, assume an integer only take 1 byte in memory.
In Python, we can perform the bitwise XOR operation using the "^" symbol. The XOR operation can be used for different purposes; XOR of two integers, XOR of two booleans, Swapping two numbers using XOR, etc. We can also use the xor() function using the operator module in Python.
In Python >> is called right shift operator. It is a bitwise operator. It requires a bitwise representation of object as first operand. Bits are shifted to right by number of bits stipulated by second operand. Leading bits as towards left as a result of shifting are set to 0.
You could just use NumPy:
In [7]: import numpy as np
In [8]: c1 = np.array(c1)
In [9]: c2 = np.array(c2)
In [10]: c1 & c2
In [11]: c1 | c2
Why not simply trying something like this using list comprehensions:
c1 = ((1, 0, 0, 0, 1, 1), (1, 1, 0, 0, 0, 1), (1, 1, 1, 0, 0, 0))
c2 = ((1, 0, 1, 1, 0, 0), (0, 1, 0, 1, 1, 0), (0, 1, 1, 0, 1, 0))
print('Bitwise or: ', [[k | l for k, l in zip(i, j)] for i, j in zip(c1, c2)])
print('Bitwise and: ', [[k & l for k, l in zip(i, j)] for i, j in zip(c1, c2)])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With