MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / binary_coded_decimal

Function binary_coded_decimal

bit_manipulation/binary_coded_decimal.py:1–23  ·  view source on GitHub ↗

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

(number: int)

Source from the content-addressed store, hash-verified

1def binary_coded_decimal(number: int) -> str:
2 """
3 Find binary coded decimal (bcd) of integer base 10.
4 Each digit of the number is represented by a 4-bit binary.
5 Example:
6 >>> binary_coded_decimal(-2)
7 '0b0000'
8 >>> binary_coded_decimal(-1)
9 '0b0000'
10 >>> binary_coded_decimal(0)
11 '0b0000'
12 >>> binary_coded_decimal(3)
13 '0b0011'
14 >>> binary_coded_decimal(2)
15 '0b0010'
16 >>> binary_coded_decimal(12)
17 '0b00010010'
18 >>> binary_coded_decimal(987)
19 '0b100110000111'
20 """
21 return "0b" + "".join(
22 str(bin(int(digit)))[2:].zfill(4) for digit in str(max(0, number))
23 )
24
25
26if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected