Use dd
or xxd
(part of Vim), for example to read one byte (-l
) at offset 100 (-s
) from binary file try:
xxd -p -l1 -s 100 file.bin
to use hex offsets, in Bash you can use this syntax $((16#64))
, e.g.:
echo $((16#$(xxd -p -l1 -s $((16#FC)) file.bin)))
which reads byte at offset FC
and print it in decimal format.
Alternatively use dd
, like:
dd if=file.bin seek=$((16#FC)) bs=1 count=5 status=none
which will dump raw data of 5 bytes at hex offset FC
.
Then you can assign it into variable, however it won't work when your data has NULL bytes, therefore either you can skip them (xxd -a
) or as workaround you can store them in plain hexadecimal format.
For example:
Read 10 bytes at offset 10 into variable which contain bytes in hex format:
hex=$(xxd -p -l 10 -s 10 file.bin)
Then write them into file or device:
xxd -r -p > out.bin <<<$hex
Here are few useful functions in Bash:
set -e
# Read single decimal value at given offset from the file.
read_value() {
file="$1"
offset="$2"
[ -n "$file" ]
[ -n "$offset" ]
echo $((16#$(xxd -p -l1 -s $offset "$file")))
}
# Read bytes in hex format at given offset from the file.
read_data() {
file="$1"
offset="$2"
count="$3:-1"
xxd -p -l $count -s $offset "$file"
}
Sample usage:
read_value file.bin $((16#FC)) # Read 0xFC offset from file.bin.
xxd -ps
andxxd -r -ps
. It would be safer.