Command-line to reverse byte order/change endianess

后端 未结 6 1237
逝去的感伤
逝去的感伤 2021-02-07 18:49

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

6条回答
  •  一向
    一向 (楼主)
    2021-02-07 19:12

    I came up with this Perl one-liner to convert 4-byte integers from one endianness to another:

    $ perl -e 'open F,shift; do { read(F,$a,4); print scalar reverse($a);} while(!eof(F));' bigend.bin > littlend.bin
    

    That probably works fine on real Linux machines, but Cygwin bit me in the end, treating the binary file as text and inserting a 0x0D (aka CR) before each 0x0A byte (aka newline). But if you pipe to cat -, it seems to leave it alone. This works for me:

    $ perl -e 'open F,shift; do { read(F,$a,4); print scalar reverse($a);} while(!eof(F));' bigend.bin | cat - > littlend.bin
    

提交回复
热议问题