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?