Working with Binary Files
Min Yang Jung | 10 Jan 2021I am a huge fan of vim. I don’t even know how to quit Emacs :) Whichever system I happen to work on, the very first tool I always check and customize is vim. After trying out a variety of plug-ins and auxilary tools around vim, I settled down with my own vimrc file and ended up using the exvim as my favorite editor. Perhaps my own customization around vim may deserve a separate write-up.
Anyway, I recently had to work with binary files and learned that vim already provides a nice way to work with binary files.
When vim loads up a binry file, its content may look like this:
With :%!xxd
, it shows up as follows:
Enabling syntax coloring makes it more readable: :set ft=xxd
At this point, it is possible to directly change hex values on the left side. Once
changes are completed, we need to go back to the previous mode before updating the file: :%!xxd -r
.
We can then now save the changes to file by :w
.
You may notice an extra 0A
is added to the end of the file that you just updated. To truncate
the last byte:
truncate --size=-1 bin_file
sed '$ s/.$//' bin_file> > output_file
(iftruncate
is not available)
Lastly, a couple well known tips that may be useful when working with binary files:
- To dump a file in the hex format:
hexdump bin_file
- To diff two binary files:
diff <(xxd binary_file1) <(xxd binary_file2)