0

I want to do some operation on binary file using python script. I have one binary file. And I want to append binary data to it.

Example:
File abc.bin is available.

Command:

python file_append.py abc.bin 1234 5678

I want to append "1234" and "5678" at the end of the binary file abc.bin.

So I opened the file with "ab" mode (append + binary). When I append a command line argument, it appends the ASCII value of the argument.

How can I append the hex value (here 1234 and 5678) at the end of the file?

Code:

fo = open(str(sys.argv[1]), 'ab')
fv = string.atoi(sys.argv[2])
ft = string.atoi(sys.argv[3])
fo.write(fv)
1
  • so you want to append 4 bytes with hexa values 12, 34, 56, and 78? Commented Sep 26, 2015 at 9:29

2 Answers 2

1

if you want to parse the command line arguments, split them into two-digit groups, interpret then these numbers as ASCII hexa codes and append this at the end of the binary file of interest, then you could do something like this

of = open(sys.argv[1], 'ab')
for arg in sys.argv[2:]:
    val = int(arg)
    for b in (val/100, val%100):
        of.write(chr(int(str(b), base=16)))

python file_append.py abc.bin 1234 5678 then produces file abc.bin the content of which can be checked with hexdump -C abc.bin which shows

00000000  12 34 56 78                                       |.4Vx|
00000004
Sign up to request clarification or add additional context in comments.

4 Comments

This won't cope with data containing hex digits > 9.
that it won't, I was assuming (perhaps mistakenly) that the input is expected to be a decimal integer...
Fair enough. But in that case, your code is still wrong, because it interprets '1234' as 0x1234 instead of 0x04d2.
as far as I can tell, it gives the same output as the approach using a2b_hex so it seems that it does what was desired (for input containing only decimal digits)...
0

I solved it with the code below.

fo = open(str(sys.argv[1]), 'ab')
f1 = binascii.a2b_hex(sys.argv[2])
fo.write(f1)
f2 = binascii.a2b_hex(sys.argv[3])
fo.write(f2)
fo.close()

Thanks for your response.

1 Comment

You could join the data strings into one string & pass that to a2b_hex, rather than converting & writing each separately. And then your program could cope with any number of data strings. Eg, binascii.a2b_hex(''.join(sys.argv[2:]))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.