mastupristi
mastupristi

Reputation: 1478

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

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

Example:

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.

Upvotes: 10

Views: 10718

Answers (1)

hansaplast
hansaplast

Reputation: 11573

# 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

Upvotes: 10

Related Questions