Reputation: 1478
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.
Upvotes: 10
Views: 10718
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 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
Upvotes: 10