-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbin2hex.go
129 lines (118 loc) · 2.39 KB
/
bin2hex.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
// ported from linux bin2hex
package main
import (
"bufio"
"encoding/binary"
"flag"
"fmt"
"log"
"os"
)
var (
iflag = flag.Bool("i", false, "mark array as init data")
cflag = flag.Bool("c", false, "mark as const array")
sflag = flag.Bool("s", false, "mark as static array")
szflag = flag.Bool("sz", false, "add size variable")
sectname = flag.String("sn", "", "specify section name")
elemsz = flag.Uint("b", 1, "element size")
endian = flag.String("e", "little", "specify endianess")
)
func main() {
flag.Parse()
if flag.NArg() < 1 {
usage()
}
var o binary.ByteOrder
switch *endian {
case "little":
o = binary.LittleEndian
case "big":
o = binary.BigEndian
default:
log.Fatalf("unsupported endian %q", *endian)
}
var (
typ string
brkline uint64
suffix string
)
switch *elemsz {
case 1:
typ = "char"
brkline = 8
case 2:
typ = "short"
brkline = 8
case 4:
typ = "int"
brkline = 4
case 8:
typ = "long long"
brkline = 4
suffix = "ull"
default:
log.Fatalf("unsupported element size %d", *elemsz)
}
id := ""
if *iflag {
id = " __initdata"
}
static := ""
if *sflag {
static = "static "
}
const_ := ""
if *cflag {
const_ = "const "
}
fmt.Printf("/* automatically generated by bin2hex */\n")
if *sectname != "" {
fmt.Printf("__attribute__((section(\"%s\")))\n", *sectname)
}
fmt.Printf("%s%sunsigned %s %s[] %s= {\n\t", static, const_, typ, flag.Arg(0), id)
r := bufio.NewReader(os.Stdin)
i := uint64(0)
for ; ; i++ {
var (
s1 uint8
s2 uint16
s4 uint32
s8 uint64
c uint64
err error
)
switch *elemsz {
case 1:
err = binary.Read(r, o, &s1)
c = uint64(s1)
case 2:
err = binary.Read(r, o, &s2)
c = uint64(s2)
case 4:
err = binary.Read(r, o, &s4)
c = uint64(s4)
case 8:
err = binary.Read(r, o, &s8)
c = uint64(s8)
}
if err != nil {
break
}
if i != 0 && i%brkline == 0 {
fmt.Printf("\n\t")
}
fmt.Printf("%#0*x%s, ", 2**elemsz, c, suffix)
}
fmt.Printf("\n};\n")
if *szflag {
if *sectname != "" {
fmt.Printf("__attribute__((section(\"%s\")))\n", *sectname)
}
fmt.Printf("%s%sint %s = %d;\n", static, const_, flag.Arg(0), i)
}
}
func usage() {
fmt.Fprintln(os.Stderr, "usage: [-i] firmware")
flag.PrintDefaults()
os.Exit(1)
}