Python Forum

Full Version: Shorter or more descriptive?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Which one should I commit?

for i in range(0, len(data), 2):
  decimal_number = int(data[i:i + 2], 16)
  binary_number = bin(decimal_number)[2:]
  byte = binary_number.zfill(8)
  self.rom[int(first_byte_address, 16) + i // 2] = byte
or

for i in range(0, len(data), 2):
  self.rom[int(first_byte_address, 16) + i // 2] = f'{int(data[i:i + 2], 16):08b}'
The second one looks better, but here is another possibility
base = int(first_byte_address, 16)
for k, s in enumerate((data[i:i+2] for i in range(0, len(data), 2)), base):
    rom[k] = f'{int(s, 16):08b}'
I would use binacsii.unhexlify to convert the str or bytes hex representation into bytes.

Then using the fact that bytes yields integers if you iterate over it.
Same with index access.


import binascii


def to_bin(data: str) -> list[str]:

    data = binascii.unhexlify(data)

    def transformer():
        for char in data:
            yield f"{char:08b}"

    return list(transformer())
I made a closure, because it looks nicer.
The difference is here, that noting is mutated.
You get a new list.