forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_to_excess3.py
More file actions
34 lines (25 loc) · 886 Bytes
/
Copy pathbinary_to_excess3.py
File metadata and controls
34 lines (25 loc) · 886 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def binary_to_excess3(binary_str: str) -> str:
"""
Convert a binary number (as a string) to its Excess-3 code.
https://en.wikipedia.org/wiki/Excess-3
Args:
binary_str (str): Binary number as a string (e.g., "1010").
Returns:
str: Excess-3 code as a binary string.
Example:
>>> binary_to_excess3("1010")
'1101'
"""
# Convert binary to decimal
decimal_value = int(binary_str, 2)
# Add 3 (Excess-3 encoding)
excess3_value = decimal_value + 3
# Convert back to 4-bit binary
excess3_binary = format(excess3_value, "04b")
return excess3_binary
if __name__ == "__main__":
from dostest import testmod
testmod()
binary_input = input("Enter a 4-bit binary number: ")
excess3_output = binary_to_excess3(binary_input)
print(f"Excess-3 code of {binary_input} is: {excess3_output}")