Command-line to reverse byte order/change endianess

Alexander Torstling picture Alexander Torstling · Jun 22, 2011 · Viewed 16.3k times · Source

I'm hacking around in some scripts trying to parse some data written by Javas DataOutputStream#writeLong(...). Since java always seems to write big endian, I have a problem feeding the bytes to od. This is due to the fact that od always assumes that the endianess matches the endianess of the arch that you are currently on, and I'm on a little endian machine.

I'm looking for an easy one-liner to reverse the byte order. Let's say that you know that the last 8 bytes of a file is a long written by the aforementioned writeLong(...) method. My current best attempt to print this long is

tail -c 8 file | tac | od -t d8

, but tac only seems to work on text (fair enough). I've found some references to dd conv=swab, but this only swaps bytes in pairs, and cannot reverse these eight bytes.

Does anyone know a good one-liner for this?

Answer

Marc picture Marc · Oct 10, 2013

You could use objcopy:

$ objcopy -I binary -O binary --reverse-bytes=num inputfile.bin outputfile.bin

where num is either 2 or 4.