最近使用txt文件進行數據處理的時候,突然發現txt文件是怎樣編碼數據的了,它是以二進制來進行存儲的嗎?為了知道這個情況,我使用hexdump工具進行查看txt文件的二進制形式,並順道進行學習了hexdump文件的使用:
hexdump 一般用來查看“二進制”文件的十六進制編碼,但實際上它能查看任何文件,而不只限於二進制文件:
hexdump [選項] [文件]…
-n length:格式化輸出文件的前length個字節 -C:輸出規范的十六進制和ASCII碼 -b:單字節八進制顯示 -c:單字節字符顯示 -d:雙字節十進制顯示 -o:雙字節八進制顯示 -x:雙字節十六進制顯示 -s:從偏移量開始輸出 -e 指定格式字符串,格式字符串由單引號包含,格式字符串形如:’a/b “format1” “format2”。每個格式字符串由三部分組成,每個由空格分割,如a/b表示,b表示對每b個輸入字節應用format1格式,a表示對每個a輸入字節應用format2,一般a>b,且b只能為1,2,4,另外a可以省略,省略a=1。format1和format2中可以使用類似printf的格斯字符串。
%02d:兩位十進制 %03x:三位十六進制 %02o:兩位八進制 %c:單個字符等 %_ad:標記下一個輸出字節的序號,用十進制表示 %_ax:標記下一個輸出字節的序號,用十六進制表示 %_ao:標記下一個輸出字節的序號,用八進制表示 %_p:對不能以常規字符顯示的用.代替 同一行顯示多個格式字符串,可以跟多個-e選項
常用命令:
格式化輸出文件 hexdump test 格式化輸出文件的前10個字節 hexdump -n 10 test 格式化輸出文件的前10個字節,並以16進制顯示 hexdump -n 10 -C test 格式化輸出從20開始的10個字節,並以16進制顯示 hexdump -n 10 -C -s 20
使用hexdump 查看文本文件:
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
hexdump -C hexdump.txt
查看結果:
可見,txt文件本身是沒有任何格式的,只是對ascii字符進行轉譯;所以txt文件也能以 'rb' 二進制的形式進行打開並按照每次
8個bit進行讀取,並進行解析;
參考文件: