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.

66 lines
1.3 KiB

3 years ago
  1. package modhex
  2. import (
  3. "errors"
  4. "fmt"
  5. )
  6. const hexChars = "0123456789abcdef"
  7. const modhexChars = "cbdefghijklnrtuv"
  8. var modhex2HexMap map[byte]byte
  9. var hex2ModhexMap map[byte]byte
  10. func init() {
  11. hex2ModhexMap = make(map[byte]byte)
  12. for i, h := range []byte(hexChars) {
  13. hex2ModhexMap[h] = modhexChars[i]
  14. }
  15. modhex2HexMap = make(map[byte]byte)
  16. for i, m := range []byte(modhexChars) {
  17. modhex2HexMap[m] = hexChars[i]
  18. }
  19. }
  20. // EncodeHex encodes a hex string into a modhex string
  21. func EncodeHex(hex string) (string, error) {
  22. size := len([]byte(hex))
  23. if size%2 == 1 {
  24. return "", errors.New("size of input hex input not even")
  25. }
  26. var modhex = make([]byte, size)
  27. for i, h := range []byte(hex) {
  28. if m, ok := hex2ModhexMap[h]; ok {
  29. modhex[i] = m
  30. } else {
  31. return "", fmt.Errorf("input not hex encoded; position %d", i)
  32. }
  33. }
  34. return string(modhex), nil
  35. }
  36. // DecodeHex decodes a modhex string into a hex string
  37. func DecodeHex(modhex string) (string, error) {
  38. size := len([]byte(modhex))
  39. if size%2 == 1 {
  40. return "", errors.New("size of modhex input not even")
  41. }
  42. var hex = make([]byte, size)
  43. for i, m := range []byte(modhex) {
  44. if h, ok := modhex2HexMap[m]; ok {
  45. hex[i] = h
  46. } else {
  47. return "", fmt.Errorf("input not modhex encoded; position %d", i)
  48. }
  49. }
  50. return string(hex), nil
  51. }