Skip to content

Added binery_or_operator.py to bit manipulation file #2331

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Aug 27, 2020
Merged
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions bit_manipulation/binary_or_operator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""
https://www.tutorialspoint.com/python3/bitwise_operators_example.htm
This function takes in 2 integer, convert them to binary and returns a binary
in str format that is the result of an Binary OR operation from the 2 integer
input.

Returns a binary resulted from 2 integer input in str format
>>> binary_or(25,32)
'0b111001'

>>> binary_or(37,50)
'0b110111'

>>> binary_or(21,30)
'0b11111'

>>> binary_or(58,73)
'0b1111011'
"""


def binary_or(a : int, b : int):
if isinstance(a, float) or isinstance(b, float):
raise TypeError("'Float' object cannot be implemented as an integer")
if isinstance(a, str) or isinstance(b, str):
raise TypeError("'str' object cannot be implemented as an integer")
if a < 0 or b < 0:
raise ValueError("the value of both input must be positive")
"""
a_binary and b_binary are the binary of a and b in str format
"""
a_binary = str(bin(a))[2:]
b_binary = str(bin(b))[2:]
binary = []
max_len = max(len(a_binary), len(b_binary))
a_binary = a_binary.zfill(max_len)
b_binary = b_binary.zfill(max_len)
for char_a, char_b in zip(a_binary, b_binary):
if char_a == "1" or char_b == "1":
binary.append("1")
else:
binary.append("0")
return "0b" + "".join(binary)


if __name__ == "__main__":
import doctest
doctest.testmod()