numeric.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package qr
  2. import (
  3. "errors"
  4. "fmt"
  5. "strconv"
  6. "github.com/boombuler/barcode/utils"
  7. )
  8. func encodeNumeric(content string, ecl ErrorCorrectionLevel) (*utils.BitList, *versionInfo, error) {
  9. contentBitCount := (len(content) / 3) * 10
  10. switch len(content) % 3 {
  11. case 1:
  12. contentBitCount += 4
  13. case 2:
  14. contentBitCount += 7
  15. }
  16. vi := findSmallestVersionInfo(ecl, numericMode, contentBitCount)
  17. if vi == nil {
  18. return nil, nil, errors.New("To much data to encode")
  19. }
  20. res := new(utils.BitList)
  21. res.AddBits(int(numericMode), 4)
  22. res.AddBits(len(content), vi.charCountBits(numericMode))
  23. for pos := 0; pos < len(content); pos += 3 {
  24. var curStr string
  25. if pos+3 <= len(content) {
  26. curStr = content[pos : pos+3]
  27. } else {
  28. curStr = content[pos:]
  29. }
  30. i, err := strconv.Atoi(curStr)
  31. if err != nil || i < 0 {
  32. return nil, nil, fmt.Errorf("\"%s\" can not be encoded as %s", content, Numeric)
  33. }
  34. var bitCnt byte
  35. switch len(curStr) % 3 {
  36. case 0:
  37. bitCnt = 10
  38. case 1:
  39. bitCnt = 4
  40. break
  41. case 2:
  42. bitCnt = 7
  43. break
  44. }
  45. res.AddBits(i, bitCnt)
  46. }
  47. addPaddingAndTerminator(res, vi)
  48. return res, vi, nil
  49. }