Skip to content

Add binary_coded_decimal.py #10656

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 10 commits into from
Oct 17, 2023
29 changes: 29 additions & 0 deletions bit_manipulation/binary_coded_decimal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
def binary_coded_decimal(number: int) -> str:
"""
Find binary coded decimal (bcd) of integer base 10.
Each digit of the number is represented by a 4-bit binary.
Example:
>>> binary_coded_decimal(-2)
'0b0000'
>>> binary_coded_decimal(-1)
'0b0000'
>>> binary_coded_decimal(0)
'0b0000'
>>> binary_coded_decimal(3)
'0b0011'
>>> binary_coded_decimal(2)
'0b0010'
>>> binary_coded_decimal(12)
'0b00010010'
>>> binary_coded_decimal(987)
'0b100110000111'
"""
return "0b" + "".join(
str(bin(int(digit)))[2:].zfill(4) for digit in str(max(0, number))
)


if __name__ == "__main__":
import doctest

doctest.testmod()