Vim Tips Wiki
Register
Advertisement
Tip 1613 Printable Monobook Previous Next

created 2009 · complexity basic · version 7.0


Vim is not designed to edit binary files, but it is possible provided care is taken to avoid automatic formatting that might break a binary file. Vim is distributed with the xxd utility that provides a convenient method to dump a binary file to hex. You can edit the printable hex characters, and use xxd to reverse the process to write an updated binary file. It is possible to automate the hex conversion but knowing how it works will give you a more versatile tool.

Dumping a binary file as hex[]

You can read a hex dump from a binary file into the current buffer. The following command inserts a hex dump of the file sample.bin after the line holding the cursor:

:r !xxd sample.bin

Lines similar to the following would be inserted into the buffer:

0000000: 0001 0203 3031 3233 0405 0607 4445 4647  ....0123....DEFG
0000010: 1011 1213 1415 1617 1819 1a1b 1c1d 1e1f  ................

The left column shows the offset of the first byte on each line. The middle column shows the bytes in hex, in groups of two (in the example, the first byte is hex 00, followed by hex 01, 02, 03, 30, 31 etc). The right column shows the printable text, if any (the last byte on the first line is hex 47 which is the ASCII code for "G").

You can read the xxd usage text into the current Vim buffer with:

:r !xxd --help

Generating C source for a binary file[]

In a C program, you may want an array that holds data equivalent to the contents of a binary file. The following command reads a dump of file sample.bin, formatted as C source:

:r !xxd -i sample.bin

Using the same binary file as earlier, the result would be:

unsigned char sample_bin[] = {
  0x00, 0x01, 0x02, 0x03, 0x30, 0x31, 0x32, 0x33, 0x04, 0x05, 0x06, 0x07,
  0x44, 0x45, 0x46, 0x47, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
};
unsigned int sample_bin_len = 32;

Editing binary files[]

Use the -b option to set binary mode before editing a binary file, for example:

vim -b myfile.bin

If wanted, you can display nonprintable characters in hex, and you can wrap lines:

:setlocal display=uhex
:setlocal wrap

In normal mode, type g then Ctrl-G to display the byte number at the cursor, or type a byte number then go to jump to that byte (for example, 123go will jump to byte number 123). The first byte in the file has byte number 1.

The following command replaces the buffer with a hex dump:

:%!xxd

You can edit the hex bytes, then convert the file back to binary with the command:

:%!xxd -r

The above command reverses the hex dump by converting the hex bytes to binary (the printable text in the right column is ignored).

See also[]

References[]

Comments[]

Advertisement