-1

I'm working on a 6809 python processor emulator for educational purposes.

I have a short binary file on the hard drive. The data is raw assembler output for a Motorola MC6809 that has the following contents:

0000300000338cfd4f5f10eec9100012126ec90010adc900186e4c12124cb10255270339121232624f5cf1025527046e4c12126ec4ff00000000

Actual code data:

338cfd4f5f10eec9100012126ec90010adc900186e4c12124cb10255270339121232624f5cf1025527046e4c12126ec4

Using python3.9 how do I get this into a list mem[] as either:

mem[00,00,30,00,00,33,8c,fd,4f,5f,...]

I suspect since ascii characters are involved here quotes would be needed

or

mem[0x00,0x00,0x30,0x00,0x00,0x33,0x8c,0xfd,0x4f,0x5f,...]

all I can seem to do is get the data back as

mem[b'00',b'00',b'30',b'00',b'00',b'33'.b'8c',b'fe',b'4f',b'5f',...]

But I can't seem to typecast these byte values into anything usable.

I've tried a half a dozen methods, with some questionable/unusable results.

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
  • Does this answer your question? [Reading a binary file with python](https://stackoverflow.com/questions/8710456/reading-a-binary-file-with-python) – bfris Aug 26 '21 at 23:14
  • "a list mem[] " *what*? That doesn't make any sense in Python. What, **exactly** is the object you require? – juanpa.arrivillaga Aug 27 '21 at 03:39
  • You need to tell us *precisely* what your input is, and *precisely* what you are trying to create. Otherwise, this isn't on-topic for StackOverflow. – juanpa.arrivillaga Aug 27 '21 at 03:40

2 Answers2

1

Your question implies that you have a file full of ASCII characters, but your self-answer contradicts that by converting single bytes into integers.

It turns out that bytes are already integers. All you need to do is convert the bytes that you read into a list. You could probably work with the bytes object directly, but who am I to judge.

with open("/home/me/Documents/Sources/procproject.BIN", "rb") as memin:
    mem = list(memin.read())
Mark Ransom
  • 286,393
  • 40
  • 379
  • 604
0

thank you for your time and replies
struct is not really a straight up simple method, but I found a rather interesting and simple way to get a byte array into a hex integer array

==========


    mem = []
    memin = open("/home/me/Documents/Sources/procproject.BIN", "rb")
    
    while True:
        mp = bytes(memin.read(1))
        if mp == b'':
            break
        mem.append(hex(int.from_bytes(mp, 'big'))) #this is the magic#
    memin.close()
    mem=mem[5:]
    mem = mem[:-5]

==========
works like a charm

  • That is not a "hex integer" array. This is a `list` of string objects. Not sure why you would think this is useful. You should really carefully consider @MarkRansom answer – juanpa.arrivillaga Aug 27 '21 at 03:41