小结
本文记录了使用Linux指令将Hex文件与二进制文件的相互转换。
问题及解决
在很多情况下需要将Hex内容的问题转换成二进制文件,另外的情况是,需要将二进制文件转换成Hex内容的文件。例如:需要进行hex字符串存在文件里进行加解密运算时,需要转换成二进制后存在文件中,再进行运算。
使用以下xdd指令:
[john@localhost ~]$ cat hex.txt #原始文件
5fc6e719bb7a887e32f0c1fc273121a7cc036bb8d3ffa9499821743235a73391
[john@localhost ~]$ xxd -r -p hex.txt hex.bin #转换成二进制文件
[john@localhost ~]$ cat hex.bin #输出二进制文件
_���z�~2���'1!��k����I�!t25�3�
[john@localhost ~]$ xxd hex.bin #hexdump格式输出
0000000: 5fc6 e719 bb7a 887e 32f0 c1fc 2731 21a7 _....z.~2...'1!.
0000010: cc03 6bb8 d3ff a949 9821 7432 35a7 3391 ..k....I.!t25.3.
[john@localhost ~]$ xxd -p hex.bin #从二进制文件转换回简单hex文件
5fc6e719bb7a887e32f0c1fc273121a7cc036bb8d3ffa9499821743235a73391
[john@localhost ~]$
以下是-p
和-r
的说明:
-p | -ps | -postscript | -plain
output in postscript continuous hexdump style. Also known as plain hexdump style.
-r | -revert
reverse operation: convert (or patch) hexdump into binary. If not writing to stdout,
xxd writes into its output file without truncating it. Use the combination -r -p to
read plain hexadecimal dumps without line number information and without a particular col‐
umn layout. Additional Whitespace and line-breaks are allowed anywhere.
参考
Linux, Scripting & programming: Hexdump: Hexdump a binary file and convert it back
Stackoverflow: Transform hexadecimal information to binary using a Linux command