-
Notifications
You must be signed in to change notification settings - Fork 4
/
binprint.go
78 lines (63 loc) · 1.23 KB
/
binprint.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
package main
import (
"flag"
"fmt"
"io"
"log"
"os"
"strconv"
"strings"
)
var (
offset = flag.Int("o", 0, "binary location offset")
status = 0
)
func main() {
log.SetPrefix("binprint: ")
log.SetFlags(0)
flag.Usage = usage
flag.Parse()
var args []string
if flag.NArg() < 1 {
buf, err := io.ReadAll(os.Stdin)
ck(err)
str := strings.TrimSpace(string(buf))
str = strings.Replace(str, "\n", " ", -1)
args = strings.Split(str, " ")
} else {
args = flag.Args()
}
for _, a := range args {
if a == "" {
continue
}
n, err := strconv.ParseUint(a, 0, 64)
if err != nil {
n, err = strconv.ParseUint(a, 16, 64)
}
if err != nil {
fmt.Fprintf(os.Stderr, "invalid number %q\n", a)
status = 1
continue
}
bits := fmt.Sprintf("%b", n)
fmt.Printf("%#x %d -> %b {\n", n, n, n)
for i := len(bits) - 1; i >= 0; i-- {
if bits[i] == '1' {
fmt.Printf("\t%d -> %c\n", *offset+len(bits)-1-i, bits[i])
}
}
fmt.Printf("}\n")
}
os.Exit(status)
}
func ck(err error) {
if err != nil {
log.Fatal(err)
}
}
func usage() {
fmt.Fprintln(os.Stderr, "usage: binprint [options] num ...")
flag.PrintDefaults()
os.Exit(2)
}