1

i came across a binary file (i guess) i try to generate using my script, so maybe i do it perfectly wrong, but so far it worked. Now i'm stuck and don't feel i can understand (and as a noob to binary files, can't name the problem correctly to google any answer)..

I read the "target file" as a binary file and i found it is like many "\x00" with several numeric values in between (like "\x05").

What i do is like:

def myEncode(a):
    if   a == 2: A = "\x02"
    elif a == 5: A = "\x05"
    return(A)

line = "\x00\x00\x01" + myEncode(5) + "\x00"
phrase = bytearray(line.encode("utf-8"))
f = open("outfile", "ab")
f. write(phrase)
f.close()
  1. it would help me a lot if i could use hex() to transform this integer 5 into "\x05", but what i get is "0x5". Which, added to the file this way doesn't work. I really need (for some reason) to make it look "\x" and 2-digit number

  2. the more important: i need to add decimal 128 (hexadecimal "\x80") and bigger. For a reason beyond my understanding it always inserts "\xc2\x80". When i create the same file using the original program, it only adds this "\x80", so i guess it must work somehow, yet i don't know why..

Thanks for any advice, hint or a direction where to look.

peta
  • 11
  • 2
  • `phrase = bytes([0, 0, 1, 5, 0])`. See: [Binary Sequence Types](https://docs.python.org/3/library/stdtypes.html#binary-sequence-types-bytes-bytearray-memoryview). – ekhumoro Sep 24 '20 at 10:52
  • try `r"\x{:02x}".format(120)` – geckos Sep 24 '20 at 11:35
  • Thank you guys for helping me so much and so quickly. The "bytes" works perfectly to me (and appeared more understandable to me at first sight). I will study both the other option and the link as soon as i get over my deadline – peta Sep 24 '20 at 20:15

0 Answers0