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.

87 lines
1.9 KiB

3 years ago
3 years ago
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. // display usage if no data is provided
  28. if flag.NArg() < 1 {
  29. flag.Usage()
  30. os.Exit(0)
  31. }
  32. if decode {
  33. // decode was selected
  34. // read the modhex string from the command line
  35. src := []byte(strings.Join(flag.Args(), " "))
  36. // create a buffer to hold the decoded data
  37. dst := make([]byte, modhex.DecodedLen(len(src)))
  38. // decode the input
  39. _, err := modhex.Decode(dst, src)
  40. if err != nil {
  41. // report the error to the user
  42. fmt.Fprintln(os.Stderr, err)
  43. os.Exit(-1)
  44. }
  45. // should the output be a hex string?
  46. if hexdata {
  47. // print out the decoded data as a hex string
  48. fmt.Println(hex.EncodeToString(src))
  49. } else {
  50. // print out the decoded bytes stdout
  51. os.Stdout.Write(dst)
  52. }
  53. } else {
  54. // encode was selected
  55. // read the input data
  56. var src []byte
  57. if hexdata {
  58. // read the input as a hex string
  59. var err error
  60. src, err = hex.DecodeString(flag.Arg(0))
  61. if err != nil {
  62. // report the hex decode error and exit
  63. fmt.Fprintf(os.Stderr, "modhex: %s\n", err)
  64. os.Exit(-1)
  65. }
  66. } else {
  67. // read the input as bytes
  68. src = []byte(strings.Join(flag.Args(), ""))
  69. }
  70. // encode the input
  71. s := modhex.EncodeToString(src)
  72. // print out the modhex encoded string
  73. fmt.Println(s)
  74. }
  75. }