what do i do wrong with encoding hexadecimal "40" in Python?

69 views Asked by At

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.

0

There are 0 answers