forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhex_to_bin.py
56 lines (47 loc) · 1.46 KB
/
hex_to_bin.py
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
defhex_to_bin(hex_num: str) ->int:
"""
Convert a hexadecimal value to its binary equivalent
#https://stackoverflow.com/questions/1425493/convert-hex-to-binary
Here, we have used the bitwise right shift operator: >>
Shifts the bits of the number to the right and fills 0 on voids left as a result.
Similar effect as of dividing the number with some power of two.
Example:
a = 10
a >> 1 = 5
>>> hex_to_bin("AC")
10101100
>>> hex_to_bin("9A4")
100110100100
>>> hex_to_bin(" 12f ")
100101111
>>> hex_to_bin("FfFf")
1111111111111111
>>> hex_to_bin("-fFfF")
-1111111111111111
>>> hex_to_bin("F-f")
Traceback (most recent call last):
...
ValueError: Invalid value was passed to the function
>>> hex_to_bin("")
Traceback (most recent call last):
...
ValueError: No value was passed to the function
"""
hex_num=hex_num.strip()
ifnothex_num:
raiseValueError("No value was passed to the function")
is_negative=hex_num[0] =="-"
ifis_negative:
hex_num=hex_num[1:]
try:
int_num=int(hex_num, 16)
exceptValueError:
raiseValueError("Invalid value was passed to the function")
bin_str=""
whileint_num>0:
bin_str=str(int_num%2) +bin_str
int_num>>=1
returnint(("-"+bin_str) ifis_negativeelsebin_str)
if__name__=="__main__":
importdoctest
doctest.testmod()