I've just started the "advanced" stages of the Python 2.7 course on Codeacademy and went to the extra effort of trying to write a function to perform a manual bitwise OR (|
) operation.
What I came up with is not the most readable solution (so not so Pythonic)...
def bitwiseOr(bin1, bin2):
"""Perform a bitwise OR swap of two string representations of a binary number"""
# if the second bit is larger (in length), swap them
if len(bin1) < len(bin2):
bin1, bin2 = bin2, bin1
# cast string into list using list comprehension
result = [x for x in bin1]
resultString = ""
# start at the end of the smallest length bit string,
# moving backwards by 1 char, and stop at the 2nd char
for i in range(len(bin2), 2, -1):
if bin2[i-1] == "1":
result[i] = bin2[i-1]
# convert the list back into a string
for item in result:
resultString += item
return resultString
print bin(0b1110 | 0b101)
print bitwiseOr("0b101", "0b1110")
The above two print
calls both return the same result (albeit with the first call returning a binary number and the second returning a string representation of a binary number).
Readability aside - I'm interested to see how it's logically done, underneath the hood, by Python internally. Poking around in the CPython repository didn't yield much, despite the fact that I think I found the right file (C is very foreign to me).
What I mean by logically is, there are normally a few ways to solve any given problem, and I solved this one by passing the base 2 representations of each number as strings, creating a list based on the larger length binary, and comparing each character, preferencing the 1.
How does Python do it internally?
This question, to the untrained eye (someone without a computer science background), is about trying to understand the C implementation of Python's bitwise OR operation.
However after some more research I've realised the question, to the trained eye, might seem absurd, since it is actually the processor itself which understands this type of operation.
What this means is that the internal logic of the Python bitwise OR operation is actually entirely dependent on the instructions available to the CPU, that is, it is not dependent on a higher level language.
So in summary, the internal logic of the Python bitwise OR operator performs a comparison on the bits (the 1's and 0's) of the machine in question, and how it performs this operation is a direct comparison of said bits which, mind-blowingly, is not dissimilar to how Ancient Egyptians performed multiplication. Woah.