二進制文件處理之尾部補0和尾部去0


背景

有時候我們需要在某個二進制文件的尾部增加一些字節,使文件大小對齊到某個邊界,以便滿足某些操作的需求。例如某個文件下一步的寫入操作需要塊對齊。

有時候我們需要將某個二進制文件尾部的大量十六進制0字節去除。例如某工具生成的文件系統鏡像,實際包含的有效數據不多,但尾部默認用0填充到了整個文件系統大小,此時會想將其尾部的0去掉以加快燒錄。

尾部補0

可以使用dd來完成。dd支持conv參數,conv指定sync,則可將每個輸入塊填充到ibs個字節,不足部分用空(NUL)字符補齊。

  sync      pad every input block with NULs to ibs-size; when used
            with block or unblock, pad with spaces rather than NULs

例如

zqb-all-PC:~$ echo "https://www.cnblogs.com/zqb-all/" > demo

zqb-all-PC:~$ dd if=demo of=demo_align bs=512 conv=sync
記錄了0+1 的讀入
記錄了1+0 的寫出
512 bytes copied, 0.000572995 s, 894 kB/s

zqb-all-PC:~$ du -b demo demo_align
33	demo
512	demo_align

zqb-all-PC:~$ hexdump -C demo ;hexdump -C demo_align
00000000  68 74 74 70 73 3a 2f 2f  77 77 77 2e 63 6e 62 6c  |https://www.cnbl|
00000010  6f 67 73 2e 63 6f 6d 2f  7a 71 62 2d 61 6c 6c 2f  |ogs.com/zqb-all/|
00000020  0a                                                |.|
00000021
00000000  68 74 74 70 73 3a 2f 2f  77 77 77 2e 63 6e 62 6c  |https://www.cnbl|
00000010  6f 67 73 2e 63 6f 6d 2f  7a 71 62 2d 61 6c 6c 2f  |ogs.com/zqb-all/|
00000020  0a 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000030  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
*
00000200

尾部去0

可以使用sed來完成,替換掉最后一行的末尾的0即可

sed '$ s/\x00*$//'  源文件  >  新文件

例如

zqb-all-PC:~$ sed '$ s/\x00*$//' demo_align > demo_cut

zqb-all-PC:~$ du -b demo_align demo_cut
512	demo_align
33	demo_cut

zqb-all-PC:~$ hexdump -C demo_align;hexdump -C demo_cut
00000000  68 74 74 70 73 3a 2f 2f  77 77 77 2e 63 6e 62 6c  |https://www.cnbl|
00000010  6f 67 73 2e 63 6f 6d 2f  7a 71 62 2d 61 6c 6c 2f  |ogs.com/zqb-all/|
00000020  0a 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000030  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
*
00000200
00000000  68 74 74 70 73 3a 2f 2f  77 77 77 2e 63 6e 62 6c  |https://www.cnbl|
00000010  6f 67 73 2e 63 6f 6d 2f  7a 71 62 2d 61 6c 6c 2f  |ogs.com/zqb-all/|
00000020  0a                                                |.|
00000021

20200406更新:本方法對大文件不適用,請參考:cut-trailing-bytes:二進制尾部去0小工具

其他

如果不是0x00,是其他的怎么處理?

尾部去0xFF,從尾部去0命令可以看出,其實是可以很方便地改成成去掉其他的字符

sed '$ s/\xFF*$//'  源文件  >  新文件

尾部補全對齊0xFF,這個暫時沒有想到很簡單方式。搜了下,找到了 https://superuser.com/questions/274972/how-to-pad-a-file-with-ff-using-dd# 但感覺還不夠好。

本文鏈接:https://www.cnblogs.com/zqb-all/p/11920964.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM