Skip to content

Commit 368ce7a

Browse files
Added a hex-bin.py file in conversion.py (#4433)
* Added a file that converts hexa to binary * Added file to convert hexadecimal to binary * Update hex-bin.py * added type hint in the code * Added doctest * Added code to handle exception * Resolved doctest issue * Update hex-bin.py * Modified convert function * Added WhiteSpace around operators. * Made more pythonic * removed whitespace * Updated doctest command * Removed whitespace * imported union * Replaced flag with is_negative * updated return type * removed pip command * Resolved doctest issue * Resolved doctest error * Reformated the code * Changes function name * Changed exception handling statements * Update and rename hex-bin.py to hex_to_bin.py * Update newton_method.py * Update matrix_operation.py * Update can_string_be_rearranged_as_palindrome.py * Update hex_to_bin.py Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 8d17343 commit 368ce7a

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

conversions/hex_to_bin.py

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
def hex_to_bin(hex_num: str) -> int:
2+
"""
3+
Convert a hexadecimal value to its binary equivalent
4+
#https://stackoverflow.com/questions/1425493/convert-hex-to-binary
5+
Here, we have used the bitwise right shift operator: >>
6+
Shifts the bits of the number to the right and fills 0 on voids left as a result.
7+
Similar effect as of dividing the number with some power of two.
8+
Example:
9+
a = 10
10+
a >> 1 = 5
11+
12+
>>> hex_to_bin("AC")
13+
10101100
14+
>>> hex_to_bin("9A4")
15+
100110100100
16+
>>> hex_to_bin(" 12f ")
17+
100101111
18+
>>> hex_to_bin("FfFf")
19+
1111111111111111
20+
>>> hex_to_bin("-fFfF")
21+
-1111111111111111
22+
>>> hex_to_bin("F-f")
23+
Traceback (most recent call last):
24+
...
25+
ValueError: Invalid value was passed to the function
26+
>>> hex_to_bin("")
27+
Traceback (most recent call last):
28+
...
29+
ValueError: No value was passed to the function
30+
"""
31+
32+
hex_num = hex_num.strip()
33+
if not hex_num:
34+
raise ValueError("No value was passed to the function")
35+
36+
is_negative = hex_num[0] == "-"
37+
if is_negative:
38+
hex_num = hex_num[1:]
39+
40+
try:
41+
int_num = int(hex_num, 16)
42+
except ValueError:
43+
raise ValueError("Invalid value was passed to the function")
44+
45+
bin_str = ""
46+
while int_num > 0:
47+
bin_str = str(int_num % 2) + bin_str
48+
int_num >>= 1
49+
50+
return int(("-" + bin_str) if is_negative else bin_str)
51+
52+
53+
if __name__ == "__main__":
54+
import doctest
55+
56+
doctest.testmod()

0 commit comments

Comments
 (0)