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.

86 lines
1.9 KiB

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