I need to modify a byte in a binary file at a certain offset.
Example:
A.bin
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
.
printf
and dd.Modify a byte in a binary file using standard Linux command line tools.
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.
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.
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.
# 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 hexadecimalxxd -r - B.bin
: reverse hexadecimal dump (xxd -r
) — take the byte number and the hexadecimal value from standard input (-
) and write to B.bin
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With