Python Forum
Shorter or more descriptive?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Shorter or more descriptive?
#1
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}'
Reply
#2
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}'
estarq likes this post
Reply
#3
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.
estarq and tester_V like this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020