Review
You don't have a lot of code here to review, so this will necessarily be short.
- PEP-8: The Style Guide for Python Code recommends:
snake_case
for functions, variables, and parameters. So aString
should be a_string
, and retVal
should be ret_val
.
- Better parameter names
- What is
aString
? "Hello World"
is a string, but we can't use it, because you are actually expecting a hexadecimal string. Perhaps hex_string
would be a better parameter name.
- Similarly,
binary_string
would be more descriptive than retStr
.
- A
'''docstring'''
would be useful for the function.
- Type hints would also be useful.
Alternate Implementation
Doing things character-by-character is inefficient. It is usually much faster to let Python do the work itself with its efficient, optimized, native code functions.
Python strings formatting supports adding a comma separator between thousand groups.
>>> f"{123456789:,d}"
'123,456,789'
It also supports adding underscores between groups of 4 digits when using the binary or hexadecimal format codes:
>>> f"{548151468:_x}"
'20ac_20ac'
>>> f"{0x20AC:_b}"
'10_0000_1010_1100'
That is most of the way to what you're looking for. Just need to turn underscores to spaces, with .replace(...)
and fill with leading zeros by adding the width and 0-fill flag to the format string.
>>> f"{0x20AC:019_b}".replace('_', ' ')
'0010 0000 1010 1100'
A function using this technique could look like:
def str_bin_in_4digits(hex_string: str) -> str:
"""
Turn a hex string into a binary string.
In the output string, binary digits are space separated in groups of 4.
>>> str_bin_in_4digits('20AC')
'0010 0000 1010 1100'
"""
value = int(hex_string, 16)
width = len(hex_string) * 5 - 1
bin_string = f"{value:0{width}_b}"
return bin_string.replace('_', ' ')
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True)
Depending on your definition of elegant, you can one-line this:
def str_bin_in_4digits(hex_string: str) -> str:
"""
Turn a hex string into a binary string.
In the output string, binary digits are space separated in groups of 4.
>>> str_bin_in_4digits('20AC')
'0010 0000 1010 1100'
"""
return f"{int(hex_string,16):0{len(hex_string)*5-1}_b}".replace('_', ' ')
binascii
module for this. (stackoverflow.com/a/1425500/10534470) \$\endgroup\$