1

I need to change one byte at a well-known position of a binary file to a specific value, and am looking for a way to achieve that using command line tools.

Constraints:

  • I need to change one single byte.
  • I know the position of the byte in the file.
  • I know what value I want in the byte. This may be anything, including non-printable characters in the 0x01–0x19 range.
  • The new value does not depend on the old value, hence no need to retrieve the old value.

To zero out the 9th byte in a file, I would do

dd if=/dev/zero of=/the/file bs=1 seek=8 count=1 conv=notrunc

If I want anything other than zero in that file, I would try piping something containing the exact bit value into dd. Something like:

spit-out-bytes | dd of=/the/file bs=1 seek=8 count=1 conv=notrunc

What would I use for spit-out-bytes?

  • 1
    You probably need conv=notrunc – wurtel Dec 3 '18 at 13:27
3

First of all, your example is wrong, it would overwrite the first byte instead of the 9th (you want seek output, not skip input). It would also truncate the file to 1 byte, if it's a regular file instead of a block device (use conv=notrunc to avoid).

dd bs=1 seek=8 count=1 conv=notrunc if=/dev/zero of=somefile

Triple check each dd command before you run it...

What would I use for spit-out-bytes?

You can try echo or printf...

$ echo -n -e '\x00\x88\xaa\xff' | hexdump -C
00000000  00 88 aa ff                                       |....|
00000004

$ printf '\x00\x88\xaa\xff' | hexdump -C
00000000  00 88 aa ff                                       |....|
00000004

On a sidenote, technically if you're sure your source will be only 1 byte large, you can skip the count=1 in the dd command. However, I prefer to leave it in as a stopgap measure just in case. It's easy to have surplus bytes in the output (e.g. echo would normally append a newline character).

  • Thanks for spotting the mistake! I’ve fixed it. – user149408 Dec 3 '18 at 13:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.