Jump to byte address in vim?

I'm investigating a mainly UTF-8 file with lot of long lines. However, the file is not entirely text file, there is some garbage. To find my point of interest I'm using hd and grep.

So at some point I know it'm interested in e.g. 0000301a, so I want to quickly open the file in Vim and jump to that position.

Example (actually a tiny file, here the position is 0000001c):

me@here:~$ hd file | grep -C 10 \ 00\ 
00000000  6c 69 6e 65 31 0a 6c 69  6e 65 32 0a 6c 69 6e 65  |line1.line2.line|
00000010  33 0a 6c 69 6e 65 34 0a  6c 69 6e 65 00 35 0a 6c  |3.line4.line.5.l|
00000020  69 6e 65 36 0a 6c 69 6e  65 37 0a 6c 69 6e 65 38  |ine6.line7.line8|
00000030  0a 6c 69 6e 65 39 0a 6c  69 6e 65 31 30 0a        |.line9.line10.|
0000003e
me@here:~$ 

Is there a trick in Vim to jump to a byte position? Or as close as possible?


Solution 1:

Yes, there is. It's the normal mode command go.

From :h go:

[count]go         Go to {count} byte in the buffer.

For example, 42go jumps to byte 42.

In order to jump to a hexadecimal or octal address you would need to construct a command with :normal! go or the equivalent :goto, and the str2nr() or printf() function.

:exe 'normal! ' . str2nr('0x2a', 16) . 'go'
:exe 'goto' str2nr('0x2a', 16)

Solution 2:

While this question has merit of its own, may I suggest that you're doing this whole thing in a rather roundabout fashion, using all of hd, grep, Vim, and the shell?

Why not use Vim and only Vim for the whole process?

The key is at :h 23.4, "Binary files": Vim can be your hex editor.

After starting Vim with your file, vim -b myfile, the workflow becomes:

:%!xxd -g1<Enter>
/00 <Enter>
...
...
:%!xxd -r<Enter>

Be sure to read :h hex-editing, too, for more details.