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.

88 lines
2.0 KiB

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