You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
1.8 KiB

3 years ago
  1. package main
  2. import (
  3. "encoding/hex"
  4. "flag"
  5. "fmt"
  6. "os"
  7. "strings"
  8. "git.trashheap.io/blinkthethings/modhex"
  9. )
  10. func main() {
  11. // configure command line flags
  12. var decode, hexdata bool
  13. flag.BoolVar(&decode, "d", false, "decode data (the default is to encode).")
  14. flag.BoolVar(&hexdata, "x", false, "Use hex encoding for non-modhex data.")
  15. flag.Usage = func() {
  16. fmt.Println("modhex - encode/decode data using modhex encoding.")
  17. fmt.Println()
  18. fmt.Println("Usage:\n\n modex [-d] [-x] <data>")
  19. fmt.Println()
  20. fmt.Println(" Convert input DATA as specified and print output to STDOUT.")
  21. fmt.Println()
  22. fmt.Printf("Flags:\n\n")
  23. flag.PrintDefaults()
  24. fmt.Println()
  25. }
  26. flag.Parse()
  27. if decode {
  28. // decode was selected
  29. // read the modhex string from the command line
  30. src := []byte(strings.Join(flag.Args(), " "))
  31. // create a buffer to hold the decoded data
  32. dst := make([]byte, modhex.DecodedLen(len(src)))
  33. // decode the input
  34. _, err := modhex.Decode(dst, src)
  35. if err != nil {
  36. // report the error to the user
  37. fmt.Fprintln(os.Stderr, err)
  38. os.Exit(-1)
  39. }
  40. // should the output be a hex string?
  41. if hexdata {
  42. // print out the decoded data as a hex string
  43. fmt.Println(hex.EncodeToString(src))
  44. } else {
  45. // print out the decoded bytes stdout
  46. os.Stdout.Write(dst)
  47. }
  48. } else {
  49. // encode was selected
  50. // read the input data
  51. var src []byte
  52. if hexdata {
  53. // read the input as a hex string
  54. var err error
  55. src, err = hex.DecodeString(flag.Arg(0))
  56. if err != nil {
  57. // report the hex decode error and exit
  58. fmt.Fprintf(os.Stderr, "modhex: %s\n", err)
  59. os.Exit(-1)
  60. }
  61. } else {
  62. // read the input as bytes
  63. src = []byte(strings.Join(flag.Args(), ""))
  64. }
  65. // encode the input
  66. s := modhex.EncodeToString(src)
  67. // print out the modhex encoded string
  68. fmt.Println(s)
  69. }
  70. }