1

How can I do calculations with vim Macros?

I have a question related to the above question ( how to do calculations in vim with an example of.csv), how can we achieve hexadecimal calculations with similar examples used in above question.

2
  • Welcome to Vi and Vim! In the future, it helps to move the relevant details from the link into the question so that the question stands alone (with the link for supporting content).
    – D. Ben Knoble
    Commented Mar 27, 2021 at 15:47
  • Be sure to read this if you haven't already: vi.stackexchange.com/help/someone-answers
    – B Layer
    Commented Mar 27, 2021 at 17:39

1 Answer 1

3

Vim happily converts hex and octal number strings to decimal numbers when you use them in an arithmetic expression. So all you need to do is convert the arithmetic result back to a hex or octal formatted string.

Let's just modify the macro example from your linked answer. I'll use hex here. Octal is the same except for one character (see below). Here's the original macro sequence:

qa^"xywf,l"yywA,<C-R>=@x+@y<CR><Esc>+q

Here's the modified version:

qa^"xywf,l"yywA,<C-R>=printf("0x%x", @x+@y)<CR><Esc>+q

I just wrapped the arithmetic in a printf() call that has the hex conversion modifier %x. (Use %X if you want capital letters in the hex numbers.)

The line 0xf,0x2 will become 0xf,0x2,0x11.

For octal use %o instead (e.g. printf("0%o", ...)).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.