tags:

views:

39

answers:

2

I have a line like this:

pad (2) = 0x0041

I wanna change the hex into decimal and the expected result is

pad (2) = 65

I just tried :%s/\(.*\) = \(.*\)/\1 = \=printf("%d", submatch(2)), but it failed.

Would you help to solve this?

+2  A: 

Vim has a str2nr() function to convert different number representations to their decimal values. To convert hex values you could use it like this:

s/0x[0-9a-fA-F]\+/\=str2nr(submatch(0), 16)
sth
oh. Thank you very much and your method is quite useful.but if there are [a-f] in the statement the method fails.
stefanzweig
@stefan: Oops, yes of course :), I should extend the match to also include those characters...
sth
Thank you very much. It works definitely.
stefanzweig
+1  A: 

Your code is almost ok, but, according to the documentation:

When the substitute string starts with "\=" the remainder is interpreted as an expression. This does not work recursively: a substitute() function inside the expression cannot use "\=" for the substitute string.

So, you may change your code to

%s/\(.*\) = \(.*\)/\=submatch(1)." = ".printf("%d", submatch(2))
ZyX
Hi ZyX, Thank you very much. I will try your method. Now I have a good way to convert my logs. :-)
stefanzweig
if you're not changing anything in the first half (just matching), you might want to consider using `\zs` to change where the start of the replaced string is:
rampion
`%s/pad(.*) = \zs0x[0-9a-fA-F]\+/\=print("%d", submatch(2))`
rampion