Nigel Tao | c463f49 | 2017-07-17 17:28:19 +1000 | [diff] [blame] | 1 | // Use of this source code is governed by a BSD-style license that can be found |
| 2 | // in the LICENSE file. |
| 3 | |
| 4 | // +build ignore |
| 5 | |
| 6 | package main |
| 7 | |
| 8 | // print-bits.go prints stdin's bytes in hexadecimal and binary. |
| 9 | // |
| 10 | // Usage: go run print-bits.go < foo.bin |
| 11 | |
| 12 | import ( |
| 13 | "fmt" |
| 14 | "io" |
| 15 | "os" |
| 16 | ) |
| 17 | |
| 18 | func main() { |
| 19 | if err := main1(); err != nil { |
| 20 | os.Stderr.WriteString(err.Error() + "\n") |
| 21 | os.Exit(1) |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | func main1() error { |
| 26 | in := make([]byte, 4096) |
| 27 | bits := []byte("...._....\n") |
| 28 | os.Stdout.WriteString("offset ASCII hex binary\n") |
| 29 | for iBase := 0; ; { |
| 30 | n, err := os.Stdin.Read(in) |
| 31 | for i, x := range in[:n] { |
| 32 | bits[0] = bit(x >> 7) |
| 33 | bits[1] = bit(x >> 6) |
| 34 | bits[2] = bit(x >> 5) |
| 35 | bits[3] = bit(x >> 4) |
| 36 | bits[5] = bit(x >> 3) |
| 37 | bits[6] = bit(x >> 2) |
| 38 | bits[7] = bit(x >> 1) |
| 39 | bits[8] = bit(x >> 0) |
| 40 | ascii := rune(x) |
| 41 | if (x < 0x20) || (0x7F <= x) { |
| 42 | ascii = '.' |
| 43 | } |
| 44 | fmt.Printf("%06d %c 0x%02X 0b_%s", iBase+i, ascii, x, bits) |
| 45 | } |
| 46 | if err == io.EOF { |
| 47 | return nil |
| 48 | } |
| 49 | if err != nil { |
| 50 | return err |
| 51 | } |
| 52 | iBase += n |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | func bit(x byte) byte { |
| 57 | if x&1 != 0 { |
| 58 | return '1' |
| 59 | } |
| 60 | return '0' |
| 61 | } |