用于反转字节顺序/更改字节顺序的命令行 [英] Command-line to reverse byte order/change endianess

查看:211
本文介绍了用于反转字节顺序/更改字节顺序的命令行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一些脚本中乱砍,试图解析由Javas DataOutputStream#writeLong(...)编写的一些数据。由于java似乎总是写大端,我在将字节输入 od 时遇到问题。这是因为 od 总是假设endianess与你当前所在的arch的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.

我正在寻找一个简单的单行来反转字节顺序。假设你知道文件的最后8个字节是由前面提到的 writeLong(...)方法编写的。我目前打印这个长期的最佳尝试是

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

,但仅限 tac 似乎在文本上工作(足够公平)。我发现了一些对 dd conv = swab 的引用,但这只是成对交换字节,并且不能反转这八个字节。

, 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?

推荐答案

最终诉诸于Perl。使用我在 PERL One Liners 上找到的单行代码:

Resorted to Perl in the end. Used a one-liner which I found at PERL One Liners:

tail -c 8 file | perl -0777e 'print scalar reverse <>' | od -t d8

0777 分隔符char对我来说有点令人费解,但在debian admin的这个页面似乎暗示它是'no'的占位符记录分隔符',触发每个字节完整的反向字节。

The 0777 separator char was a bit puzzling to me, but this page at debian admin seems to suggest that it is a placeholder for 'no record separator', triggering a complete reverse byte-per byte.

欢迎提出其他建议。

编辑:在tac.c的评论中找到了另一个命令,我从GNU coreutils下载了这个命令:

Found another command in a comment to tac.c, which I downloaded from GNU coreutils:


复制每个文件,如果没有则复制标准输入给出或当遇到
FILE名称为 - 时,对于标准输出,反转记录的
顺序。记录由字符串的
实例分隔,如果没有给出,则换行符。默认情况下,
分隔符字符串附加到文件中
后面的记录末尾。

Copy each FILE, or the standard input if none are given or when a FILE name of "-" is encountered, to the standard output with the order of the records reversed. The records are separated by instances of a string, or a newline if none is given. By default, the separator string is attached to the end of the record that it follows in the file.

选项:
-b, - before将分隔符附加到文件前面的记录的起始

-r, - regex分隔符是正则表达式。
-s, - separator = separator使用SEPARATOR作为记录分隔符。

Options: -b, --before The separator is attached to the beginning of the record that it precedes in the file. -r, --regex The separator is a regular expression. -s, --separator=separator Use SEPARATOR as the record separator.

要逐字节地反转文件,请使用(在bash,ksh或sh):
tac -r -s'。\ |
'档案

To reverse a file byte by byte, use (in bash, ksh, or sh): tac -r -s '.\| ' file

这篇关于用于反转字节顺序/更改字节顺序的命令行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆