Edit binary files in Vi

Technology

cafebabe_20080809.jpg

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.

To convert a file to hex dump representation, just load your file in vi and type the following:

:%!xxd

This sends the entire contents of the opened document to xxd and loads in the result. At this point, you can view or edit any of the hex data. The ASCII representation is listed to the right, though editing this region will not affect the hex portion of the file.

When you are done, you’ll want to convert things back into their binary format before saving. To do this, you run things through xxd again, but this time with the -r option:

:%!xxd -r

Your file should be returned to illegible gibberish, which you can save back out with :wq.

A funny thing I just noticed: OS X binaries all start with the same 4 bytes which, in hex, spell out the phrase “cafe babe”. This is just a magic number used to identify the file as an OS X binary, but it’s hard not to ascribe some deeper meaning. ;)

What will the next generation of Make: look like? We’re inviting you to shape the future by investing in Make:. By becoming an investor, you help decide what’s next. The future of Make: is in your hands. Learn More.

Tagged
Discuss this article with the rest of the community on our Discord server!

ADVERTISEMENT

Escape to an island of imagination + innovation as Maker Faire Bay Area returns for its 16th iteration!

Prices Increase in....

Days
Hours
Minutes
Seconds
FEEDBACK