sponsor Vim development Vim logo Vim Book Ad

advanced Tip #1479: Convert hex to dec

 tip karma   Rating 13/6, Viewed by 3710 

Read and edit this tip on the Vim tip wiki. The wiki may have a more recent version of this tip.

created:   January 19, 2007 14:05      complexity:   advanced
author:   Aburnheimer_4t_geem41l_dot_c0m      as of Vim:  

I like vimtip #27: 'Convert hex to dec', but couldn't find the reverse function... So I took a whack at it.  This function translates all numbers decimal to hexadecimal.  Work is needed to better discriminate decimal numbers (e.g. vs. octal).

function! Dec2Hex()
    let lstr = getline(".")
    let decstr = matchstr(lstr, '\<[0-9]\+\>')
    while decstr != ""
        let decstr = printf("0x%x", decstr)
        exe 's#\<[0-9]\+\>#'.decstr."#"
     let lstr = getline(".")
        let decstr = matchstr(lstr, '\<[0-9]\+\>')
    endwhile
endfunction

Cheers!

 rate this tip  Life Changing Helpful Unfulfilling 

<< Esc in normal mode: train your brain | Show Last modified time (and others) in status bar >>

Additional Notes

Anonymous, January 31, 2007 3:48
I have this in my gvimrc for years (don't know the original source):

20nmenu  Editieren.Show.dez->hex :echo "0x".Nr2hex(32)
20nmenu  Editieren.Show.string->hex :echo "0x".String2hex("123Aa")
20nmenu  Editieren.Show.dez->char :echo nr2char(49)
20nmenu  Editieren.Show.char->dez :echo char2nr("'*")
20vmenu  Editieren.Show.dez->hex y<ESC>:echo "0x".Nr2hex(@@)
20vmenu  Editieren.Show.string->hex y<ESC>:echo "0x".String2hex(@@)
20vmenu  Editieren.Show.dez->char y<ESC>:echo nr2char(@@)
20vmenu  Editieren.Show.char->dez y<ESC>:echo char2nr(@@)


"……………………………………………………………………………………………………………………………………………………………………………………………
" The function Nr2hex() returns the Hex string of a number.
func Nr2hex(nr)
  let n = a:nr
  let r = ""
  while n
    let r = '0123456789ABCDEF'[n % 16] . r
    let n = n / 16
  endwhile
  return r
endfunc

" The function String2Hex() converts each character in a string to a two
" character Hex string.
func String2hex(str)
  let out = ''
  let ix = 0
  while ix < strlen(a:str)
    let out = out . Nr2hex(char2nr(a:str[ix]))
    let ix = ix + 1
  endwhile
  return out
endfunc


For example, just mark a number and select dec->hex in the edit menu, hit CR (or add <CR> to the menu mappings),
and you see the result in the command line. A more convenient place for the menu entries could be in the popup menu.

Thomas
Anonymous, January 21, 2007 8:01
Oops, the title of this tip must be "Convert dec to hex". ;-)
If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to the maillist. Help Bram help Uganda.
   
SourceForge.net Logo