bin2h.sh 二進制數據轉化為數組

bin2h.sh腳本

#!/bin/sh
# $0 objname < in > out
objname=${1:-objname}
od -A n -v -t x1 | sed -e '1i\
const unsigned char '$objname'[] = {
s/\([0-9a-f][0-9a-f]\) */0x\1,/g
$s/,$//
$a\
};
'

注解

  • 帶行號代碼圖片


    code.png
  • 3行, 獲取數組名

${parameter:-word}
Use Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

  • 4行,od -A n -v -t x1
    -A n 不顯示文件偏移;
    -v 不用*號省略重復行顯示
    -t x1 用一個字節的16進制格式顯示
  • 1i\ 在第一行插入 “const unsigned char 數組名[] = {”;
  • s/regexp/replacement/ 替換操作
  • 6行,將每一個字節替換成"0xNN,"的形式,最后的g表示行內全局替換;
  • 7行,第一個$表示最后一行、第二個$表示行尾,將最后一行行尾的 “,”刪除;
  • 8行, 9行, a\ 在最后添加一行“ }; ”

使用示例

bin2h.sh data < libhello.so > data.h
data.h 效果:
const unsigned char data[] = { 0x7f,0x45,0x4c,0x46,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x03,0x00,0x28,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x34,0x00,0x00,0x00, 0x1c,0x21,0x00,0x00,0x00,0x00,0x00,0x05,0x34,0x00,0x20,0x00,0x08,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x34,0x00,0x00,0x00, 0x34,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x04,0x00,0x00,0x00, 0x04,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x34,0x01,0x00,0x00,0x34,0x01,0x00,0x00, 0x34,0x01,0x00,0x00,0x13,0x00,0x00,0x00,0x13,0x00,0x00,0x00,0x04,0x00,0x00,0x00, 0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x1f,0x1e,0x00,0x00,0x1f,0x1e,0x00,0x00,0x05,0x00,0x00,0x00, 0x00,0x10,0x00,0x00,0x01,0x00,0x00,0x00,0xac,0x1e,0x00,0x00,0xac,0x2e,0x00,0x00, 0xc0,0x03,0x00,0x00,0x03,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00, 0x10,0x00,0x00,0x00,0x1b,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x02,0x00,0x00,0x00, 0x08,0x05,0x00,0x00,0x08,0x05,0x00,0x00,0xb9,0x04,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x23,0x00,0x00,0x00, 0x05,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0xc4,0x09,0x00,0x00,0xc4,0x09,0x00,0x00, 0x8c,0x01,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };

參考

  1. [Binary Hacks] Hacker's Secret 100 Secret Techniques Revealed.
    Chapter 1. 4 Using "od" to dump binary files
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容