17
\$\begingroup\$

xxd is a utility, bundled with vim, that has been used to encode answers to code golf problems on this site. It converts a binary file into a hex dump and back again.

Implement the xxd and xxd -r commands in the programming language(s) of your choice. Scoring is based on the character/byte lengths of a) your program(s) and b) any command line argument(s) necessary to switch a combined program between modes (they need not be -r). As in golf, lower scores are better.

  • For two separate programs: forward code + reverse code
  • For a combined program: combined code + sum(forward arguments) + sum(reverse arguments) - 2

Specification of the chosen xxd subset

The forward command (e.g. xxd) accepts 0 ≤ n ≤ 216 bytes from standard input and generates ceil(n / 16) lines of standard output in the following format (all hex digits lowercase):

  • Offset of the first encoded byte (format string "%07x:"); ends in "0"
  • At most 16 hex-encoded bytes, grouped into pairs (format string " %02x" for even bytes, "%02x" for odd bytes) and right-padded with spaces to 42 characters
  • The encoded bytes interpreted as ASCII characters, values not between 0x20 and 0x7e ('\40' and '\176') inclusive becoming "."
  • A newline ("\n"; "\r\n" allowed when standard output is in binary mode)

Minimal ungolfed C implementation:

#include <stdio.h>
int main() {
    unsigned char L[16];
    int t = 0, n, i, s;

    for (; (n = fread(L, 1, 16, stdin)); t += n) {
        printf("%07x:", t);
        s = 42;
        for (i = 0; i < n; i++)
            s -= printf(i & 1 ? "%02x" : " %02x", L[i]);
        printf("%*s", s, "");
        for (i = 0; i < n; i++)
            putchar(L[i] > '\37' && L[i] < '\177' ? L[i] : '.');
        printf("\n");
    }

    return 0;
}

The reverse command (e.g. xxd -r) accepts any unmodified output of the forward command (given a valid input to that command) and produces that original input.

Example usage

$ xxd < /dev/null | wc -c
0
$ php -r 'echo join(range("\0",~"\0"));' | xxd
0000000: 0001 0203 0405 0607 0809 0a0b 0c0d 0e0f  ................
0000010: 1011 1213 1415 1617 1819 1a1b 1c1d 1e1f  ................
0000020: 2021 2223 2425 2627 2829 2a2b 2c2d 2e2f   !"#$%&'()*+,-./
0000030: 3031 3233 3435 3637 3839 3a3b 3c3d 3e3f  0123456789:;<=>?
0000040: 4041 4243 4445 4647 4849 4a4b 4c4d 4e4f  @ABCDEFGHIJKLMNO
0000050: 5051 5253 5455 5657 5859 5a5b 5c5d 5e5f  PQRSTUVWXYZ[\]^_
0000060: 6061 6263 6465 6667 6869 6a6b 6c6d 6e6f  `abcdefghijklmno
0000070: 7071 7273 7475 7677 7879 7a7b 7c7d 7e7f  pqrstuvwxyz{|}~.
0000080: 8081 8283 8485 8687 8889 8a8b 8c8d 8e8f  ................
0000090: 9091 9293 9495 9697 9899 9a9b 9c9d 9e9f  ................
00000a0: a0a1 a2a3 a4a5 a6a7 a8a9 aaab acad aeaf  ................
00000b0: b0b1 b2b3 b4b5 b6b7 b8b9 babb bcbd bebf  ................
00000c0: c0c1 c2c3 c4c5 c6c7 c8c9 cacb cccd cecf  ................
00000d0: d0d1 d2d3 d4d5 d6d7 d8d9 dadb dcdd dedf  ................
00000e0: e0e1 e2e3 e4e5 e6e7 e8e9 eaeb eced eeef  ................
00000f0: f0f1 f2f3 f4f5 f6f7 f8f9 fafb fcfd feff  ................
$ xxd <<< 'The quick brown fox jumps over the lazy dog.'
0000000: 5468 6520 7175 6963 6b20 6272 6f77 6e20  The quick brown 
0000010: 666f 7820 6a75 6d70 7320 6f76 6572 2074  fox jumps over t
0000020: 6865 206c 617a 7920 646f 672e 0a         he lazy dog..
$ xxd <<< 'The quick brown fox jumps over the lazy dog.' | xxd -r
The quick brown fox jumps over the lazy dog.
\$\endgroup\$
2
  • \$\begingroup\$ Should the reverse mode ignore incorrect ASCII characters? (FWIW the actual xxd does, which is quite useful). \$\endgroup\$ Jul 3, 2013 at 8:13
  • \$\begingroup\$ @PeterTaylor: The reverse mode only has to work properly with unmodified hex dumps (start at 0000000, lowercase hex digits, 16 bytes on all lines but the last, no gaps, etc.), and input validation is not required. That said, it probably makes sense to ignore the 16-character "ASCII" column on the right, because it cannot be used to distinguish "." and non-printable characters. \$\endgroup\$ Jul 3, 2013 at 8:37

4 Answers 4

3
\$\begingroup\$

Perl, 122 + 54 = 176 122 + 45 = 167

The forward script:

$/=$,;for(<>=~/.{1,16}/gs){$h="";$h.=sprintf"%*s%02x",++$m%2,"",ord for/./gs;
s/[^ -~]/./g;printf"%06x0:%-42s",$n++,$h;say}

And the reverse script:

/:(.+?)  /,print map{chr hex}$1=~/\w\w/gfor<>

(This one is interesting; there are all kinds of obscure bugs that can show up in the reverse script depending on the input, if you're not careful.)

\$\endgroup\$
6
  • \$\begingroup\$ Since $1 is known only to contain hex digits and spaces, can you not use /\w\w/ instead of /[0-9a-f]{2}/? \$\endgroup\$
    – Neil
    Jun 19, 2016 at 8:54
  • \$\begingroup\$ $1 contains many things besides hex digits and spaces. \$\endgroup\$
    – breadbox
    Jul 4, 2016 at 20:23
  • \$\begingroup\$ In the example, I only see hex digits and spaces between the : and the ` `. \$\endgroup\$
    – Neil
    Jul 4, 2016 at 21:03
  • \$\begingroup\$ (Anyone know how to generate two monospace spaces in comment markdown?) \$\endgroup\$
    – Neil
    Jul 4, 2016 at 21:04
  • \$\begingroup\$ @Neil Never mind, I misread my own code. I don't recall now why I didn't just use /\w\w/. It seems so obvious that I feel like I must have had a reason, but I can't see one. My best guess is that it was a holdover from a version that was trying to avoid requiring the initial regex. \$\endgroup\$
    – breadbox
    Jul 4, 2016 at 21:20
3
+100
\$\begingroup\$

Javascript, 247 + 61 = 308 225 + 63 = 288

-20 or so thanks to ASCII-only

Forward:

b=>[...Array(b.length+15>>4)].map((_,i)=>(P=j=>i=>i.toString(x=16).padStart(j,0))(7)(i)+"0: "+(p=b.splice(0,x)).map(P(2)).join``.replace(/.{4}/g,"$& ").padEnd(42)+p.map(l=>String.fromCharCode(l>31&l<127?l:46)).join``).join`
`

Try it online!

Reverse:

d=>d.match(/[^:]{40}/g).join``.match(/\S\S/g).map(t=>+("0x"+t))

Try it online!

Might make an explanation at some point.

\$\endgroup\$
2
\$\begingroup\$

253

JavaScript (V8), 200 bytes

b=>{for(i=0,P=j=>i=>i.toString(16).padStart(j,0);t=b.slice(i,i+16),t+t;i+=16)print(P(7)(i)+': '+t.map(P(2)).join``.replace(/.{4}/g,"$& ").padEnd(42)+String.fromCharCode(...t.map(c=>c<32|c>126?46:c)))}

Try it online!

JavaScript (V8), 57 53 bytes

d=>d.match(/(?<=:.*)\w\w(?=.{19})/g).map(t=>"0x"+t-0)

Try it online!

optimized from Redwolf Programs's answer

\$\endgroup\$
2
\$\begingroup\$

C (clang), 222 + 108 = 330 189 + 105 = 294 186 + 104 = 290 bytes

Forward (-36 thanks to @ceilingcat):

#define P printf(
t,n,s;main(i){for(char z[16];n=read(i=0,z,16);t+=n){P"%07x:",t);for(s=42;i<n;)s-=P" %02x"+i%2,z[i++]);for(i=!P"%*s",s,"");i<n;i++)P"%c",isprint(z[i])?z[i]:46);P"\n");}}

Try it online!

Reverse (-4 thanks to @ceilingcat):

b;main(a){for(char z[80];gets(z);)for(a=9;z[a]-32;a+=5)b=strtol(z+a,0,16),b=b>>8?ntohs(b):b,printf(&b);}

Try it online!

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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