Editing a file in hex mode in Vim

Posted: 27th July 2013 by Tim in Linux, Vim
Tags: , , , , , ,

Native Vim doesn’t have a hex editing mode built in, however it is possible to edit a file in hex by converting the file back and forth using xxd. To do this, open your file in Vim and run :%!xxd. From here you can change the hex values and, when you’re done, run :%!xxd -r to convert back.

For example, in a terminal, create a file with the word “HeX” in it like so:

echo "HeX" > my_file

Next, open it in vim and run :%!xxd. Vim should display this:

0000000: 4865 580a                                HeX.

The first column, 00000000: is the character number for the first character in this line, zero indexed. In other words, the preceding 4 is the first character in the file (index 0). Don’t change this. Similarly, the Hex. at the end is the string representation of the line data. Don’t touch this either. The file contents are the middle bit: 4865 580a. Files with more data may contain multiple lines with 16 hex characters on each line. Run xxd on a larger file to see what I mean.

Let’s change the ‘X’ into ‘x’. ‘X’ in hex is 0x58 and is represented by the fifth and sixth hex numbers in the file. ‘x’ in hex is 0x78. So, using normal Vim commands, replace 58 with 78 so that your file looks like so:

0000000: 4865 780a                                HeX.

Finally, convert the file back to text using :%!xxd -r. You will see that the file now contains the string “Hex”.