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\
};
'

注解

  • 带行号代码图片


    bin2h.sh 二进制数据转化为数组_第1张图片
    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

你可能感兴趣的:(bin2h.sh 二进制数据转化为数组)