Jeri Raye schrieb:
> Hi,
> 
> Are there character based hex2bin and bin2hex functions in vim?
> Or are there scripts known that perform that functions?
> 
> I need to converted code with binairy values into hex values.
> So the line:
> 
> load s0, 01010101
> 
> needs to become
> 
> load s0, 55
> 
> Or are there S&R commands that can do that?
> 
> Rgds,
> Jeri.

:s/\<\x\x\>/\=Hex2Bin(submatch(0))/
:s/\<[01]\{8}\>/\=Bin2Hex(submatch(0))/

In Vim script:

" return the first run of binary digits found in string {bin} converted
" to (lower case) hex digits
func! Bin2Hex(bin)
    let bin = matchstr(a:bin, '[01]\+')
    if bin == ""
        return "0"
    endif
    let bin = repeat("0", PadSize(strlen(bin), 4)). bin
    let runs = split(bin, '....\zs')
    call map(runs, 's:fourbd2hd(v:val)')
    return join(runs, '')
endfunc

" return the first run of hex digits in string {hex} converted into
" binary digits (a match at "0x" is skipped)
func! Hex2Bin(hex)
    let hex = matchstr(a:hex, '\%(0x\)\...@!\x\+')
    if hex == ""
        return "0"
    endif
    return join(map(split(hex, '\m'), 's:hd2fourbd(v:val)'), '')
endfunc

" convert 4 bin digits (string) into 1 (lower case) hex digit
func! s:fourbd2hd(bd)
    let bd = a:bd
    return printf("%x", 8*bd[0] + 4*bd[1] + 2*bd[2] + bd[3])
endfunc

" convert 1 hex digit (string) into 4 bin digits
func! s:hd2fourbd(hd)
    let hd = eval("0x". a:hd)
    return (hd/8) . (hd/4%2) . (hd/2%2) . (hd%2)
endfunc

" calculate number of pad chars to make {len} a multiple of {chunksize}
func! PadSize(len, chunksize)
    return -1 + (a:chunksize - (a:len + a:chunksize - 1) % a:chunksize)
endfunc
" padsize := PadSize(len,chunksize) <=>
" 0 <= padsize < chunksize AND (len + padsize) mod chunksize = 0

" NOTE: must not use substitute() in the functions to avoid recursive
" submatch() when called from :s/.../\=.../
"   substitute(bin,'[01]\{4}', '\=s:fourbd2hd(submatch(0))', 'g')
"   substitute(a:hex, '\x', '\=s:hd2fourbd(submatch(0))', 'g')

----------------------------

Just found two conversion scripts on www.vim.org:

ConvertBase.vim : Convert to/from various numeric bases 
http://vim.sourceforge.net/scripts/script.php?script_id=54

tobase : Convert from base(2,8,10,16) to base(2-32). Also character to html 
entity.
http://vim.sourceforge.net/scripts/script.php?script_id=1583

I didn't tried them out yet.

-- 
Andy

--~--~---------~--~----~------------~-------~--~----~
You received this message from the "vim_use" maillist.
For more information, visit http://www.vim.org/maillist.php
-~----------~----~----~----~------~----~------~--~---

Reply via email to