Nigel Tao | d4372cb | 2017-10-12 11:17:41 +1100 | [diff] [blame] | 1 | // Copyright 2017 The Puffs Authors. |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
Nigel Tao | c463f49 | 2017-07-17 17:28:19 +1000 | [diff] [blame] | 14 | |
| 15 | // +build ignore |
| 16 | |
| 17 | package main |
| 18 | |
| 19 | // print-bits.go prints stdin's bytes in hexadecimal and binary. |
| 20 | // |
| 21 | // Usage: go run print-bits.go < foo.bin |
| 22 | |
| 23 | import ( |
| 24 | "fmt" |
| 25 | "io" |
| 26 | "os" |
| 27 | ) |
| 28 | |
| 29 | func main() { |
| 30 | if err := main1(); err != nil { |
| 31 | os.Stderr.WriteString(err.Error() + "\n") |
| 32 | os.Exit(1) |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | func main1() error { |
| 37 | in := make([]byte, 4096) |
| 38 | bits := []byte("...._....\n") |
Nigel Tao | adadb0f | 2017-07-20 15:36:59 +1000 | [diff] [blame] | 39 | os.Stdout.WriteString("offset xoffset ASCII hex binary\n") |
Nigel Tao | c463f49 | 2017-07-17 17:28:19 +1000 | [diff] [blame] | 40 | for iBase := 0; ; { |
| 41 | n, err := os.Stdin.Read(in) |
| 42 | for i, x := range in[:n] { |
| 43 | bits[0] = bit(x >> 7) |
| 44 | bits[1] = bit(x >> 6) |
| 45 | bits[2] = bit(x >> 5) |
| 46 | bits[3] = bit(x >> 4) |
| 47 | bits[5] = bit(x >> 3) |
| 48 | bits[6] = bit(x >> 2) |
| 49 | bits[7] = bit(x >> 1) |
| 50 | bits[8] = bit(x >> 0) |
| 51 | ascii := rune(x) |
| 52 | if (x < 0x20) || (0x7F <= x) { |
| 53 | ascii = '.' |
| 54 | } |
Nigel Tao | adadb0f | 2017-07-20 15:36:59 +1000 | [diff] [blame] | 55 | fmt.Printf("%06d 0x%04X %c 0x%02X 0b_%s", iBase+i, iBase+i, ascii, x, bits) |
Nigel Tao | c463f49 | 2017-07-17 17:28:19 +1000 | [diff] [blame] | 56 | } |
| 57 | if err == io.EOF { |
| 58 | return nil |
| 59 | } |
| 60 | if err != nil { |
| 61 | return err |
| 62 | } |
| 63 | iBase += n |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | func bit(x byte) byte { |
| 68 | if x&1 != 0 { |
| 69 | return '1' |
| 70 | } |
| 71 | return '0' |
| 72 | } |