Skip to content

Commit d5ea9a5

Browse files
adding bin_to_hexadecimal
1 parent 77b243e commit d5ea9a5

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

DIRECTORY.md

+1
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@
104104
## Conversions
105105
* [Binary To Decimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/binary_to_decimal.py)
106106
* [Binary To Octal](https://github.com/TheAlgorithms/Python/blob/master/conversions/binary_to_octal.py)
107+
* [Binary To Hexadecimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/binary_to_hexadecimal.py)
107108
* [Decimal To Any](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_any.py)
108109
* [Decimal To Binary](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_binary.py)
109110
* [Decimal To Binary Recursion](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_binary_recursion.py)

conversions/binary_to_hexadecimal.py

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
def bin_to_hexadecimal(binary_str: str) -> str:
2+
"""
3+
Converting a binary string into hexadecimal using Grouping Method
4+
5+
>>> bin_to_hexadecimal('101011111')
6+
'0x15f'
7+
>>> bin_to_hexadecimal(' 1010 ')
8+
'0x0a'
9+
>>> bin_to_hexadecimal('-11101')
10+
'-0x1d'
11+
>>> bin_to_hexadecimal('a')
12+
Traceback (most recent call last):
13+
...
14+
ValueError: Non-binary as parameter
15+
>>> bin_to_hexadecimal('')
16+
Traceback (most recent call last):
17+
...
18+
IndexError: string index out of range
19+
"""
20+
BITS_TO_HEX = {
21+
"0000": "0",
22+
"0001": "1",
23+
"0010": "2",
24+
"0011": "3",
25+
"0100": "4",
26+
"0101": "5",
27+
"0110": "6",
28+
"0111": "7",
29+
"1000": "8",
30+
"1001": "9",
31+
"1010": "a",
32+
"1011": "b",
33+
"1100": "c",
34+
"1101": "d",
35+
"1110": "e",
36+
"1111": "f",
37+
}
38+
39+
# Sanitising parameter
40+
binary_str = str(binary_str).strip()
41+
is_negative = binary_str[0] == "-"
42+
binary_str = binary_str[1:] if is_negative else binary_str
43+
44+
# Exceptions
45+
if not binary_str:
46+
raise ValueError("Empty string as parameter")
47+
if not all(char in "01" for char in binary_str):
48+
raise ValueError("Non-binary as parameter")
49+
50+
binary_str = (
51+
"0" * (4 * (divmod(len(binary_str), 4)[0] + 1) - len(binary_str)) + binary_str
52+
)
53+
54+
hexadecimal = []
55+
for x in range(0, len(binary_str), 4):
56+
hexadecimal.append(BITS_TO_HEX[binary_str[x : x + 4]])
57+
pass
58+
hexadecimal_str = "0x" + "".join(hexadecimal)
59+
60+
return "-" + hexadecimal_str if is_negative else hexadecimal_str
61+
62+
63+
if __name__ == "__main__":
64+
from doctest import testmod
65+
66+
testmod()

0 commit comments

Comments
 (0)