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

Function bin_to_hexadecimal

conversions/binary_to_hexadecimal.py:21–60  ·  view source on GitHub ↗

Converting a binary string into hexadecimal using Grouping Method >>> bin_to_hexadecimal('101011111') '0x15f' >>> bin_to_hexadecimal(' 1010 ') '0x0a' >>> bin_to_hexadecimal('-11101') '-0x1d' >>> bin_to_hexadecimal('a') Traceback (most recent call last):

(binary_str: str)

Source from the content-addressed store, hash-verified

19
20
21def bin_to_hexadecimal(binary_str: str) -> str:
22 """
23 Converting a binary string into hexadecimal using Grouping Method
24
25 >>> bin_to_hexadecimal('101011111')
26 '0x15f'
27 >>> bin_to_hexadecimal(' 1010 ')
28 '0x0a'
29 >>> bin_to_hexadecimal('-11101')
30 '-0x1d'
31 >>> bin_to_hexadecimal('a')
32 Traceback (most recent call last):
33 ...
34 ValueError: Non-binary value was passed to the function
35 >>> bin_to_hexadecimal('')
36 Traceback (most recent call last):
37 ...
38 ValueError: Empty string was passed to the function
39 """
40 # Sanitising parameter
41 binary_str = str(binary_str).strip()
42
43 # Exceptions
44 if not binary_str:
45 raise ValueError("Empty string was passed to the function")
46 is_negative = binary_str[0] == "-"
47 binary_str = binary_str[1:] if is_negative else binary_str
48 if not all(char in "01" for char in binary_str):
49 raise ValueError("Non-binary value was passed to the function")
50
51 binary_str = (
52 "0" * (4 * (divmod(len(binary_str), 4)[0] + 1) - len(binary_str)) + binary_str
53 )
54
55 hexadecimal = []
56 for x in range(0, len(binary_str), 4):
57 hexadecimal.append(BITS_TO_HEX[binary_str[x : x + 4]])
58 hexadecimal_str = "0x" + "".join(hexadecimal)
59
60 return "-" + hexadecimal_str if is_negative else hexadecimal_str
61
62
63if __name__ == "__main__":

Callers

nothing calls this directly

Calls 1

appendMethod · 0.45

Tested by

no test coverage detected