How do I convert all hexadecimal numbers to decimal in Vim?
Answer
:%s/0x\x\+/\=str2nr(submatch(0), 16)/g
Explanation
When cleaning logs, protocol dumps, or generated code, you may need to normalize 0x... literals into decimal quickly. Vim's expression replacement (\=) can evaluate each match and compute a converted value inline. This avoids external scripts and keeps the transformation fully repeatable in-editor.
How it works
:%s/.../.../gruns a global substitute over the whole buffer0x\x\+matches hexadecimal literals like0x1A,0xff,0x10\=tells substitute to evaluate the replacement as Vimscriptsubmatch(0)returns the full matched literalstr2nr(..., 16)converts that match from base-16 to decimal text
Every hex match is replaced by its decimal equivalent in one pass.
Example
Input:
mask=0xff
offset=0x10
limit=0x1a
Run:
:%s/0x\x\+/\=str2nr(submatch(0), 16)/g
Output:
mask=255
offset=16
limit=26
Tips
- Restrict scope with a range, for example
:'<,'>s/.../.../gfor a visual selection. - Add
cflag (.../gc) if you want confirmation per match. - Keep a macro or command-line history entry for repeated data-cleaning tasks.