tags:

views:

446

answers:

5

I have this column in a file I'm editing in VIM:

16128
16132
16136
16140
# etc...

And I want to convert it to this column:

0x3f00
0x3f04
0x3f08
0x3f0c
# etc...

How can I do this in VIM?

+1  A: 

Convert decimal to hex

Brandon E Taylor
This is a bit redundant in recent Vim's as there is a printf function. Very useful in Vim 6.x though!
Al
Thanks for the info, Al. Looks like its time to refresh my vim knowledge.
Brandon E Taylor
+3  A: 

another way, to pass it to awk

awk '{printf "0x%x\n",$1}' file
ghostdog74
+2  A: 

Select (VISUAL) the block of lines that contains the numbers, and then:

:!perl -ne 'printf "0x\%x\n", $_'
depesz
Why use perl when Vim has an internal printf?
Al
+12  A: 

Use printf (analogous to C's sprintf) with the \= command to handle the replacement:

:%s/\d\+/\=printf("0x%04x", submatch(0))

Details:

  • :%s/\d\+/ : Match one or more digits (\d\+) on any line (:%) and substitute (s).
  • \= : for each match, replace with the result of the following expression:
  • printf("0x%04x", : produce a string using the format "0x%04x", which corresponds to a literal 0x followed by a four digit (or more) hex number, padded with zeros.
  • submatch(0) : The result of the complete match (i.e. the number).

For more information, see:

:help printf()
:help submatch()
:help sub-replace-special
:help :s
Al
+1 nice (... and the remaining 15 characters)
stefanB
+4  A: 

Yet another way:

:rubydo $_ = '0x%x' % $_

Or:

:perldo $_ = sprintf '0x%x', $_

This is a bit less typing and you avoid a level of quoting / shell escaping that you'd get if you did this via :!. You need Perl / Ruby support compiled into your Vim.

Brian Carper
And it's easier than remembering how to use Vimscript, if (like most people) you use it far less often than Perl and Ruby.
ephemient