Friday, July 6, 2012

Re: How to write a text line as binary/Hex with a filename by means of Vim command line(s)?

On Wed, Jul 4, 2012 at 3:19 AM, John Beckett <johnb.beckett@gmail.com>
wrote:

> " Write a binary file (no newline at end) of characters translated
> " from pairs of hex ASCII characters (no spaces) on current line.
> function! WriteChars(outfile, text)
> let chars = ''
> for i in range(0, len(a:text)-1, 2)
> let chars .= nr2char('0x'.a:text[i : i+1])
> endfor
> call writefile([chars], a:outfile, 'b')
> endfunction
> command! WriteChars call WriteChars('data.bin', getline('.'))
>
> Put above in file writechars.vim.
> In Vim, enter:
> :so writechars.vim
>
> Put cursor on wanted line and enter (type :Wr and press Tab):
> :WriteChars
>
> File data.bin now contains the four characters.
>
> John

I took the liberty of tweaking the function slightly to both work off
multiple lines (defaulting to the current line) and to take the name of
the file as an argument. (I also moved it into my autoload functions,
but have left that bit out in the version below.)

" From John Beckett: johnb.beckett@gmail.com
" (Modified to work off multiple lines and accept spaces between
numbers by Salman Halim on Friday, July 06, 2012.)
" Write a binary file (no newline at end) of characters translated
from pairs of hex ASCII characters (no spaces) on selected lines
(defaults to current line).
" 41 61
" 2C2E
" 2D
function! WriteChars( outfile, lines )
let chars = ''

for line in a:lines
let i = 0

while ( i <= len( line ) - 1 )
if ( line[ i ] !~ '\s' )
let chars .= nr2char( '0x' . line[ i : i + 1 ] )

let i += 1
endif

let i += 1
endwhile
endfor

call writefile( [ chars ], a:outfile, 'b' )
endfunction

command! -range -nargs=1 -complete=file WriteChars call WriteChars(
<q-args>, getline( <line1>, <line2> ) )

Changes:

1. Takes the name of the output file as a command-line argument.

2. Accepts multiple lines (selected visually, for example) as the input,
defaulting to the first line otherwise.

3. Will skip over intervening whitespace.

Regards,

Salman

--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

No comments: