Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert hexadecimal to decimal in a substitution statement?

Tags:

vim

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?

like image 804
stefanzweig Avatar asked Jun 07 '10 10:06

stefanzweig


2 Answers

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)
like image 105
sth Avatar answered Sep 22 '22 07:09

sth


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))
like image 40
ZyX Avatar answered Sep 22 '22 07:09

ZyX