| @ -0,0 +1,81 @@ | |||
| package main | |||
| import ( | |||
| "encoding/hex" | |||
| "flag" | |||
| "fmt" | |||
| "os" | |||
| "strings" | |||
| "git.trashheap.io/blinkthethings/modhex" | |||
| ) | |||
| func main() { | |||
| // configure command line flags | |||
| var decode, hexdata bool | |||
| flag.BoolVar(&decode, "d", false, "decode data (the default is to encode).") | |||
| flag.BoolVar(&hexdata, "x", false, "Use hex encoding for non-modhex data.") | |||
| flag.Usage = func() { | |||
| fmt.Println("modhex - encode/decode data using modhex encoding.") | |||
| fmt.Println() | |||
| fmt.Println("Usage:\n\n modex [-d] [-x] <data>") | |||
| fmt.Println() | |||
| fmt.Println(" Convert input DATA as specified and print output to STDOUT.") | |||
| fmt.Println() | |||
| fmt.Printf("Flags:\n\n") | |||
| flag.PrintDefaults() | |||
| fmt.Println() | |||
| } | |||
| flag.Parse() | |||
| if decode { | |||
| // decode was selected | |||
| // read the modhex string from the command line | |||
| src := []byte(strings.Join(flag.Args(), " ")) | |||
| // create a buffer to hold the decoded data | |||
| dst := make([]byte, modhex.DecodedLen(len(src))) | |||
| // decode the input | |||
| _, err := modhex.Decode(dst, src) | |||
| if err != nil { | |||
| // report the error to the user | |||
| fmt.Fprintln(os.Stderr, err) | |||
| os.Exit(-1) | |||
| } | |||
| // should the output be a hex string? | |||
| if hexdata { | |||
| // print out the decoded data as a hex string | |||
| fmt.Println(hex.EncodeToString(src)) | |||
| } else { | |||
| // print out the decoded bytes stdout | |||
| os.Stdout.Write(dst) | |||
| } | |||
| } else { | |||
| // encode was selected | |||
| // read the input data | |||
| var src []byte | |||
| if hexdata { | |||
| // read the input as a hex string | |||
| var err error | |||
| src, err = hex.DecodeString(flag.Arg(0)) | |||
| if err != nil { | |||
| // report the hex decode error and exit | |||
| fmt.Fprintf(os.Stderr, "modhex: %s\n", err) | |||
| os.Exit(-1) | |||
| } | |||
| } else { | |||
| // read the input as bytes | |||
| src = []byte(strings.Join(flag.Args(), "")) | |||
| } | |||
| // encode the input | |||
| s := modhex.EncodeToString(src) | |||
| // print out the modhex encoded string | |||
| fmt.Println(s) | |||
| } | |||
| } | |||