Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • 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.

  • I can use Bash and standard commands like printf and dd.
  • I can easily write a byte into a binary file, but I don't know how to read it.

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

like image 383
mastupristi Avatar asked Jan 23 '17 12:01

mastupristi


People also ask

How can I edit a binary file?

To open the Binary Editor on an existing file, go to menu File > Open > File, select the file you want to edit, then select the drop arrow next to the Open button, and choose Open With > Binary Editor.

How do I edit a bin file in Ubuntu?

xxd is a linux command. Once the file is open, press ESC and then type :%! xxd -b and then press ENTER . Press ESC and then i for "INSERT" mode which allows you to edit.

Can VI edit binary files?

If you've ever wanted to examine or edit a binary file in your favorite text editor, there's an easy way to simulate a vi hex mode. To do this, you just filter the file's contents through the xxd hex dump utility, a trick that can be accomplished right within the vi/vim interface.


1 Answers

# 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
like image 69
hansaplast Avatar answered Sep 28 '22 19:09

hansaplast