Skip to content

Commit 23274cc

Browse files
committed
fix: return 0 from hex_to_bin("0") instead of raising
For 0 the loop builds no bit, so int("") raised ValueError: invalid literal for int() with base 10: ''. The same happened for "00" and "-0".
1 parent 6e03a48 commit 23274cc

1 file changed

Lines changed: 3 additions & 0 deletions

File tree

‎conversions/hex_to_bin.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ def hex_to_bin(hex_num: str) -> int:
1919
1111111111111111
2020
>>> hex_to_bin("-fFfF")
2121
-1111111111111111
22+
>>> hex_to_bin("0")
23+
0
2224
>>> hex_to_bin("F-f")
2325
Traceback (most recent call last):
2426
...
@@ -46,6 +48,7 @@ def hex_to_bin(hex_num: str) -> int:
4648
while int_num > 0:
4749
bin_str = str(int_num % 2) + bin_str
4850
int_num >>= 1
51+
bin_str = bin_str or "0"
4952

5053
return int(("-" + bin_str) if is_negative else bin_str)
5154

0 commit comments

Comments
 (0)