Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

Why does the xxd command not respect byte grouping when operated in reverse?

Writer Andrew Mclaughlin

I am trying to write bytes to a file on my system in a script, and I decided to use xxd (with -r) to achieve this. However, I want it to take endianness into account for each 4 bytes. here is an example i used to test this:

 echo "1122334455667788" | xxd -r -p -g 4 - outfile

I get the following output when i do hexdump outfile:

 0000000 2211 4433 6655 8877 0000008

Because I used -g 4, I expect the result to be like this

 0000000 4433 2211 8877 6655 0000008

It is not behaving like I expect it to. What am I doing wrong here?

EDIT:

I realise now that -g does is not supposed to change the byte ordering. However, xxd does take endianness into account as in the examples I provided. The question now is how can I get xxd to flip bytes in groups of 4 bytes (32-bit little endian values) instead of every 2 bytes to get the result I wanted? is this even possible with xxd alone?

2

1 Answer

Because the -g option is meant to be used in the direct (not reverse) conversion and only to format the output as seen by an user:

$ printf '\x20\x21\x22\x23\x24\x25\x26\x27\n' !"#$%&'
$ printf '\x20\x21\x22\x23\x24\x25\x26\x27\n' | xxd
00000000: 2021 2223 2425 2627 0a !"#$%&'.
$ printf '\x20\x21\x22\x23\x24\x25\x26\x27\n' | xxd -g 4
00000000: 20212223 24252627 0a !"#$%&'.

To get the presentation of byte values to change the order of Most Significant Bit you need a tool that actually could do the transformation:

printf '\x20\x21\x22\x23\x24\x25\x26\x27\n' | od -An -tx4 23222120 27262524 0000000a

And then use xxd to reverse those byte values to actual bytes:

printf '\x20\x21\x22\x23\x24\x25\x26\x27\n' | od -An -tx4 | xxd -r -p
#"! '&%$

Note that the order of the individual bytes has been reversed in each group of four bytes.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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