Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Command-line to reverse byte order/change endianess

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?

like image 726
Alexander Torstling Avatar asked Jun 22 '11 10:06

Alexander Torstling


People also ask

Does endianness affect bit order?

Bit order usually follows the same endianness as the byte order for a given computer system. That is, in a big endian system the most significant bit is stored at the lowest bit address; in a little endian system, the least significant bit is stored at the lowest bit address.

What is reverse byte order?

Description. The Byte Reversal block changes the order of the bytes in data that you input to the block. Use this block when a process communicates between target computers that use different endianness, such as between Intel® processors that are little endian and other processors that are big endian.

Does endianness affect array order?

Endianness only affects the order of bytes (not bits) in a data word. Since a char is always one-byte in size, you don't have to do any adjustments to them. The standard library function ntohl changes the byte order of an unsigned integer ( l ) from network byte order ( n ) to host byte order ( h ).

Do bytes have endianness?

When a value larger than byte is stored or serialized into multiple bytes, the choice of the order in which the component bytes are stored is called byte order, or endian, or endianness. Historically, there have been three byte orders in use: "big-endian", "little-endian", and "PDP-endian" or "middle-endian".


2 Answers

You could use objcopy:

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

where num is either 2 or 4.

like image 101
Marc Avatar answered Sep 22 '22 14:09

Marc


Used dd, Luke!

dd if=sourcefile of=resultfile conv=swab
like image 37
Anton Chevychalov Avatar answered Sep 21 '22 14:09

Anton Chevychalov