alphanumeric.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package qr
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/boombuler/barcode"
  6. )
  7. var alphaNumericTable map[byte]int = map[byte]int{
  8. '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,
  9. 'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15, 'G': 16, 'H': 17, 'I': 18, 'J': 19,
  10. 'K': 20, 'L': 21, 'M': 22, 'N': 23, 'O': 24, 'P': 25, 'Q': 26, 'R': 27, 'S': 28, 'T': 29,
  11. 'U': 30, 'V': 31, 'W': 32, 'X': 33, 'Y': 34, 'Z': 35, ' ': 36, '$': 37, '%': 38, '*': 39,
  12. '+': 40, '-': 41, '.': 42, '/': 43, ':': 44,
  13. }
  14. func encodeAlphaNumeric(content string, ecl ErrorCorrectionLevel) (*barcode.BitList, *versionInfo, error) {
  15. contentLenIsOdd := len(content)%2 == 1
  16. contentBitCount := (len(content) / 2) * 11
  17. if contentLenIsOdd {
  18. contentBitCount += 6
  19. }
  20. vi := findSmallestVersionInfo(ecl, alphaNumericMode, contentBitCount)
  21. if vi == nil {
  22. return nil, nil, errors.New("To much data to encode")
  23. }
  24. res := new(barcode.BitList)
  25. res.AddBits(int(alphaNumericMode), 4)
  26. res.AddBits(len(content), vi.charCountBits(alphaNumericMode))
  27. for idx := 0; idx < len(content)/2; idx++ {
  28. c1, ok1 := alphaNumericTable[content[idx*2]]
  29. c2, ok2 := alphaNumericTable[content[(idx*2)+1]]
  30. if !ok1 || !ok2 {
  31. return nil, nil, fmt.Errorf("\"%s\" can not be encoded as %s", content, AlphaNumeric)
  32. }
  33. res.AddBits(c1*45+c2, 11)
  34. }
  35. if contentLenIsOdd {
  36. c1, ok := alphaNumericTable[content[len(content)-1]]
  37. if !ok {
  38. return nil, nil, fmt.Errorf("\"%s\" can not be encoded as %s", content, AlphaNumeric)
  39. }
  40. res.AddBits(c1, 6)
  41. }
  42. addPaddingAndTerminator(res, vi)
  43. return res, vi, nil
  44. }