alphanumeric-data.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. var Mode = require('./mode')
  2. /**
  3. * Array of characters available in alphanumeric mode
  4. *
  5. * As per QR Code specification, to each character
  6. * is assigned a value from 0 to 44 which in this case coincides
  7. * with the array index
  8. *
  9. * @type {Array}
  10. */
  11. var ALPHA_NUM_CHARS = [
  12. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  13. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
  14. 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  15. ' ', '$', '%', '*', '+', '-', '.', '/', ':'
  16. ]
  17. function AlphanumericData (data) {
  18. this.mode = Mode.ALPHANUMERIC
  19. this.data = data
  20. }
  21. AlphanumericData.getBitsLength = function getBitsLength (length) {
  22. return 11 * Math.floor(length / 2) + 6 * (length % 2)
  23. }
  24. AlphanumericData.prototype.getLength = function getLength () {
  25. return this.data.length
  26. }
  27. AlphanumericData.prototype.getBitsLength = function getBitsLength () {
  28. return AlphanumericData.getBitsLength(this.data.length)
  29. }
  30. AlphanumericData.prototype.write = function write (bitBuffer) {
  31. var i
  32. // Input data characters are divided into groups of two characters
  33. // and encoded as 11-bit binary codes.
  34. for (i = 0; i + 2 <= this.data.length; i += 2) {
  35. // The character value of the first character is multiplied by 45
  36. var value = ALPHA_NUM_CHARS.indexOf(this.data[i]) * 45
  37. // The character value of the second digit is added to the product
  38. value += ALPHA_NUM_CHARS.indexOf(this.data[i + 1])
  39. // The sum is then stored as 11-bit binary number
  40. bitBuffer.put(value, 11)
  41. }
  42. // If the number of input data characters is not a multiple of two,
  43. // the character value of the final character is encoded as a 6-bit binary number.
  44. if (this.data.length % 2) {
  45. bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i]), 6)
  46. }
  47. }
  48. module.exports = AlphanumericData