How do I edit a binary file in hex mode using Vim?
Answer
:%!xxd
Explanation
Vim can serve as a hex editor by piping buffer contents through xxd, a hex dump utility that ships with Vim. This lets you inspect and modify individual bytes in binary files like executables, images, or data formats directly within Vim.
How it works
:%!xxdpipes the entire buffer throughxxd, converting binary content to a readable hex dump- Edit the hex values in the left column (the ASCII representation on the right is ignored when converting back)
:%!xxd -rconverts the hex dump back to binary- Save with
:wto write the modified binary
Example
" Open a binary file
vim -b data.bin
" Convert to hex view
:%!xxd
The buffer now shows:
00000000: 4865 6c6c 6f20 576f 726c 640a 5468 6973 Hello World.This
00000010: 2069 7320 6120 7465 7374 0a is a test.
" Edit the hex values, then convert back
:%!xxd -r
" Save the binary
:w
Tips
- Always open binary files with
vim -bor:set binaryto prevent Vim from adding a trailing newline or converting line endings - Only edit the hex columns on the left — changes to the ASCII preview on the right side are ignored by
xxd -r - Use
:set display=uhexto display unprintable characters as hex in normal mode without the full hex dump view - You can visually select a range and pipe just that range through
xxdfor partial hex viewing