10

I need to modify a byte in a binary file at a certain offset.

Example:

  • Input file: A.bin
  • Output file: B.bin

I need to read a byte at the offset 0x40c from A.bin, clear to 0 least significant 2 bits of this byte, and then write file B.bin equal to A.bin, but with the calculated byte at offset 0x40c.

Modify a byte in a binary file using standard Linux command line tools.

3

1 Answer 1

11
# Read one byte at offset 40C
b_hex=$(xxd -seek $((16#40C)) -l 1 -ps A.bin -)

# Delete the three least significant bits
b_dec=$(($((16#$b_hex)) & $((2#11111000))))
cp A.bin B.bin

# Write one byte back at offset 40C
printf "00040c: %02x" $b_dec | xxd -r - B.bin

It was tested in Bash and Z shell (zsh) on OS X and Linux.

The last line explained:

  • 00040c: is the offset xxd should write to
  • %02x converts $b from decimal to hexadecimal
  • xxd -r - B.bin: reverse hexadecimal dump (xxd -r) — take the byte number and the hexadecimal value from standard input (-) and write to B.bin
Sign up to request clarification or add additional context in comments.

9 Comments

I have upvoted your answer because I like it, but the OP asked for two different files, so cp A.bin B.bin should be put somewhere before the final dd, which would operate on B.bin; and, more importantly, this doesn’t work if $b equals ASCII NUL ...
@Dario thanks for pointing out that it should operate on a new file, added that in
If I replace the last line of your script with printf "00040c: %02x" $b | xxd -r - B.bin it works in all cases, because if $b is NUL (or, equivalently for my shell, an empty string) it gets expanded by %02x as 00. xxd is a standard command line tool as dd is.
@Dario thanks for the xxd suggestion. I altered the last line and also the reading. Now I don't need the ord function anymore so the code is now stripped down to 4 lines. Can you proofread that I didn't add any errors?
Re "take the line number": But it is a binary file(?).
|

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.