bashshellhexendiannessxxd

In Unix shell, how to convert from hex string to stdout bytes in machine-endian order


I'd like to run a command similar to:

# echo 00: 0123456789abcdef | xxd -r | od -tx1
0000000 01 23 45 67 89 ab cd ef
0000010

That is, I'd like to input a hex string and have it converted to bytes on stdout. However, I'd like it to respect byte order of the machine I'm on, which is little endian. Here's the proof:

# lscpu | grep Byte.Order
Byte Order:            Little Endian

So, I'd like it to work as above if my machine was big-endian. But since it isn't, I'd like to see:

# <something different here> | od -tx1
0000000 ef cd ab 89 67 45 23 01
0000010

Now, xxd has a "-e" option for little endianess. But 1) I want machine endianess, because I'd like something that works on big or little endian machines, and 2) "-e" isn't support with "-r" anyway.

Thanks!


Solution

  • What about this —

    $ echo 00: 0123456789abcdef | xxd -r | xxd -g 8 -e | xxd -r | od -tx1
    0000000    ef  cd  ab  89  67  45  23  01
    0000010
    

    According to man xxd:

    • -e

      Switch to little-endian hexdump. This option treats byte groups as words in little-endian byte order. The default grouping of 4 bytes may be changed using -g. This option only applies to hexdump, leaving the ASCII (or EBCDIC) representation unchanged. The command line switches -r, -p, -i do not work with this mode.

    • -g bytes | -groupsize bytes

      Separate the output of every bytes bytes (two hex characters or eight bit-digits each) by a whitespace. Specify -g 0 to suppress grouping. Bytes defaults to 2 in normal mode, 4 in little-endian mode and 1 in bits mode. Grouping does not apply to postscript or include style.