2 * QR Code generator library (C++)
4 * Copyright (c) Project Nayuki. (MIT License)
5 * https://www.nayuki.io/page/qr-code-generator-library
7 * Permission is hereby granted, free of charge, to any person obtaining a copy of
8 * this software and associated documentation files (the "Software"), to deal in
9 * the Software without restriction, including without limitation the rights to
10 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11 * the Software, and to permit persons to whom the Software is furnished to do so,
12 * subject to the following conditions:
13 * - The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 * - The Software is provided "as is", without warranty of any kind, express or
16 * implied, including but not limited to the warranties of merchantability,
17 * fitness for a particular purpose and noninfringement. In no event shall the
18 * authors or copyright holders be liable for any claim, damages or other
19 * liability, whether in an action of contract, tort or otherwise, arising from,
20 * out of or in connection with the Software or the use or other dealings in the
42 QrSegment::Mode::Mode(int mode, int cc0, int cc1, int cc2) :
44 numBitsCharCount[0] = cc0;
45 numBitsCharCount[1] = cc1;
46 numBitsCharCount[2] = cc2;
50 int QrSegment::Mode::getModeBits() const {
55 int QrSegment::Mode::numCharCountBits(int ver) const {
56 return numBitsCharCount[(ver + 7) / 17];
60 const QrSegment::Mode QrSegment::Mode::NUMERIC (0x1, 10, 12, 14);
61 const QrSegment::Mode QrSegment::Mode::ALPHANUMERIC(0x2, 9, 11, 13);
62 const QrSegment::Mode QrSegment::Mode::BYTE (0x4, 8, 16, 16);
63 const QrSegment::Mode QrSegment::Mode::KANJI (0x8, 8, 10, 12);
64 const QrSegment::Mode QrSegment::Mode::ECI (0x7, 0, 0, 0);
67 QrSegment QrSegment::makeBytes(const vector<uint8_t> &data) {
68 if (data.size() > static_cast<unsigned int>(INT_MAX))
69 throw std::length_error("Data too long");
71 for (uint8_t b : data)
73 return QrSegment(Mode::BYTE, static_cast<int>(data.size()), std::move(bb));
77 QrSegment QrSegment::makeNumeric(const char *digits) {
82 for (; *digits != '\0'; digits++, charCount++) {
84 if (c < '0' || c > '9')
85 throw std::domain_error("String contains non-numeric characters");
86 accumData = accumData * 10 + (c - '0');
88 if (accumCount == 3) {
89 bb.appendBits(static_cast<uint32_t>(accumData), 10);
94 if (accumCount > 0) // 1 or 2 digits remaining
95 bb.appendBits(static_cast<uint32_t>(accumData), accumCount * 3 + 1);
96 return QrSegment(Mode::NUMERIC, charCount, std::move(bb));
100 QrSegment QrSegment::makeAlphanumeric(const char *text) {
105 for (; *text != '\0'; text++, charCount++) {
106 const char *temp = std::strchr(ALPHANUMERIC_CHARSET, *text);
108 throw std::domain_error("String contains unencodable characters in alphanumeric mode");
109 accumData = accumData * 45 + static_cast<int>(temp - ALPHANUMERIC_CHARSET);
111 if (accumCount == 2) {
112 bb.appendBits(static_cast<uint32_t>(accumData), 11);
117 if (accumCount > 0) // 1 character remaining
118 bb.appendBits(static_cast<uint32_t>(accumData), 6);
119 return QrSegment(Mode::ALPHANUMERIC, charCount, std::move(bb));
123 vector<QrSegment> QrSegment::makeSegments(const char *text) {
124 // Select the most efficient segment encoding automatically
125 vector<QrSegment> result;
126 if (*text == '\0'); // Leave result empty
127 else if (isNumeric(text))
128 result.push_back(makeNumeric(text));
129 else if (isAlphanumeric(text))
130 result.push_back(makeAlphanumeric(text));
132 vector<uint8_t> bytes;
133 for (; *text != '\0'; text++)
134 bytes.push_back(static_cast<uint8_t>(*text));
135 result.push_back(makeBytes(bytes));
141 QrSegment QrSegment::makeEci(long assignVal) {
144 throw std::domain_error("ECI assignment value out of range");
145 else if (assignVal < (1 << 7))
146 bb.appendBits(static_cast<uint32_t>(assignVal), 8);
147 else if (assignVal < (1 << 14)) {
149 bb.appendBits(static_cast<uint32_t>(assignVal), 14);
150 } else if (assignVal < 1000000L) {
152 bb.appendBits(static_cast<uint32_t>(assignVal), 21);
154 throw std::domain_error("ECI assignment value out of range");
155 return QrSegment(Mode::ECI, 0, std::move(bb));
159 QrSegment::QrSegment(Mode md, int numCh, const std::vector<bool> &dt) :
164 throw std::domain_error("Invalid value");
168 QrSegment::QrSegment(Mode md, int numCh, std::vector<bool> &&dt) :
171 data(std::move(dt)) {
173 throw std::domain_error("Invalid value");
177 int QrSegment::getTotalBits(const vector<QrSegment> &segs, int version) {
179 for (const QrSegment &seg : segs) {
180 int ccbits = seg.mode.numCharCountBits(version);
181 if (seg.numChars >= (1L << ccbits))
182 return -1; // The segment's length doesn't fit the field's bit width
183 if (4 + ccbits > INT_MAX - result)
184 return -1; // The sum will overflow an int type
185 result += 4 + ccbits;
186 if (seg.data.size() > static_cast<unsigned int>(INT_MAX - result))
187 return -1; // The sum will overflow an int type
188 result += static_cast<int>(seg.data.size());
194 bool QrSegment::isAlphanumeric(const char *text) {
195 for (; *text != '\0'; text++) {
196 if (std::strchr(ALPHANUMERIC_CHARSET, *text) == nullptr)
203 bool QrSegment::isNumeric(const char *text) {
204 for (; *text != '\0'; text++) {
206 if (c < '0' || c > '9')
213 QrSegment::Mode QrSegment::getMode() const {
218 int QrSegment::getNumChars() const {
223 const std::vector<bool> &QrSegment::getData() const {
228 const char *QrSegment::ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
232 int QrCode::getFormatBits(Ecc ecl) {
234 case Ecc::LOW : return 1;
235 case Ecc::MEDIUM : return 0;
236 case Ecc::QUARTILE: return 3;
237 case Ecc::HIGH : return 2;
238 default: throw std::logic_error("Assertion error");
243 QrCode QrCode::encodeText(const char *text, Ecc ecl) {
244 vector<QrSegment> segs = QrSegment::makeSegments(text);
245 return encodeSegments(segs, ecl);
249 QrCode QrCode::encodeBinary(const vector<uint8_t> &data, Ecc ecl) {
250 vector<QrSegment> segs{QrSegment::makeBytes(data)};
251 return encodeSegments(segs, ecl);
255 QrCode QrCode::encodeSegments(const vector<QrSegment> &segs, Ecc ecl,
256 int minVersion, int maxVersion, int mask, bool boostEcl) {
257 if (!(MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= MAX_VERSION) || mask < -1 || mask > 7)
258 throw std::invalid_argument("Invalid value");
260 // Find the minimal version number to use
261 int version, dataUsedBits;
262 for (version = minVersion; ; version++) {
263 int dataCapacityBits = getNumDataCodewords(version, ecl) * 8; // Number of data bits available
264 dataUsedBits = QrSegment::getTotalBits(segs, version);
265 if (dataUsedBits != -1 && dataUsedBits <= dataCapacityBits)
266 break; // This version number is found to be suitable
267 if (version >= maxVersion) { // All versions in the range could not fit the given data
268 std::ostringstream sb;
269 if (dataUsedBits == -1)
270 sb << "Segment too long";
272 sb << "Data length = " << dataUsedBits << " bits, ";
273 sb << "Max capacity = " << dataCapacityBits << " bits";
275 throw data_too_long(sb.str());
278 if (dataUsedBits == -1)
279 throw std::logic_error("Assertion error");
281 // Increase the error correction level while the data still fits in the current version number
282 for (Ecc newEcl : vector<Ecc>{Ecc::MEDIUM, Ecc::QUARTILE, Ecc::HIGH}) { // From low to high
283 if (boostEcl && dataUsedBits <= getNumDataCodewords(version, newEcl) * 8)
287 // Concatenate all segments to create the data bit string
289 for (const QrSegment &seg : segs) {
290 bb.appendBits(static_cast<uint32_t>(seg.getMode().getModeBits()), 4);
291 bb.appendBits(static_cast<uint32_t>(seg.getNumChars()), seg.getMode().numCharCountBits(version));
292 bb.insert(bb.end(), seg.getData().begin(), seg.getData().end());
294 if (bb.size() != static_cast<unsigned int>(dataUsedBits))
295 throw std::logic_error("Assertion error");
297 // Add terminator and pad up to a byte if applicable
298 size_t dataCapacityBits = static_cast<size_t>(getNumDataCodewords(version, ecl)) * 8;
299 if (bb.size() > dataCapacityBits)
300 throw std::logic_error("Assertion error");
301 bb.appendBits(0, std::min(4, static_cast<int>(dataCapacityBits - bb.size())));
302 bb.appendBits(0, (8 - static_cast<int>(bb.size() % 8)) % 8);
303 if (bb.size() % 8 != 0)
304 throw std::logic_error("Assertion error");
306 // Pad with alternating bytes until data capacity is reached
307 for (uint8_t padByte = 0xEC; bb.size() < dataCapacityBits; padByte ^= 0xEC ^ 0x11)
308 bb.appendBits(padByte, 8);
310 // Pack bits into bytes in big endian
311 vector<uint8_t> dataCodewords(bb.size() / 8);
312 for (size_t i = 0; i < bb.size(); i++)
313 dataCodewords[i >> 3] |= (bb.at(i) ? 1 : 0) << (7 - (i & 7));
315 // Create the QR Code object
316 return QrCode(version, ecl, dataCodewords, mask);
320 QrCode::QrCode(int ver, Ecc ecl, const vector<uint8_t> &dataCodewords, int msk) :
321 // Initialize fields and check arguments
323 errorCorrectionLevel(ecl) {
324 if (ver < MIN_VERSION || ver > MAX_VERSION)
325 throw std::domain_error("Version value out of range");
326 if (msk < -1 || msk > 7)
327 throw std::domain_error("Mask value out of range");
329 size_t sz = static_cast<size_t>(size);
330 modules = vector<vector<bool> >(sz, vector<bool>(sz)); // Initially all white
331 isFunction = vector<vector<bool> >(sz, vector<bool>(sz));
333 // Compute ECC, draw modules
334 drawFunctionPatterns();
335 const vector<uint8_t> allCodewords = addEccAndInterleave(dataCodewords);
336 drawCodewords(allCodewords);
339 if (msk == -1) { // Automatically choose best mask
340 long minPenalty = LONG_MAX;
341 for (int i = 0; i < 8; i++) {
344 long penalty = getPenaltyScore();
345 if (penalty < minPenalty) {
347 minPenalty = penalty;
349 applyMask(i); // Undoes the mask due to XOR
352 if (msk < 0 || msk > 7)
353 throw std::logic_error("Assertion error");
355 applyMask(msk); // Apply the final choice of mask
356 drawFormatBits(msk); // Overwrite old format bits
359 isFunction.shrink_to_fit();
363 int QrCode::getVersion() const {
368 int QrCode::getSize() const {
373 QrCode::Ecc QrCode::getErrorCorrectionLevel() const {
374 return errorCorrectionLevel;
378 int QrCode::getMask() const {
383 bool QrCode::getModule(int x, int y) const {
384 return 0 <= x && x < size && 0 <= y && y < size && module(x, y);
388 std::string QrCode::toSvgString(int border) const {
390 throw std::domain_error("Border must be non-negative");
391 if (border > INT_MAX / 2 || border * 2 > INT_MAX - size)
392 throw std::overflow_error("Border too large");
394 std::ostringstream sb;
395 sb << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
396 sb << "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n";
397 sb << "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" viewBox=\"0 0 ";
398 sb << (size + border * 2) << " " << (size + border * 2) << "\" stroke=\"none\">\n";
399 sb << "\t<rect width=\"100%\" height=\"100%\" fill=\"#FFFFFF\"/>\n";
400 sb << "\t<path d=\"";
401 for (int y = 0; y < size; y++) {
402 for (int x = 0; x < size; x++) {
403 if (getModule(x, y)) {
404 if (x != 0 || y != 0)
406 sb << "M" << (x + border) << "," << (y + border) << "h1v1h-1z";
410 sb << "\" fill=\"#000000\"/>\n";
416 void QrCode::drawFunctionPatterns() {
417 // Draw horizontal and vertical timing patterns
418 for (int i = 0; i < size; i++) {
419 setFunctionModule(6, i, i % 2 == 0);
420 setFunctionModule(i, 6, i % 2 == 0);
423 // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
424 drawFinderPattern(3, 3);
425 drawFinderPattern(size - 4, 3);
426 drawFinderPattern(3, size - 4);
428 // Draw numerous alignment patterns
429 const vector<int> alignPatPos = getAlignmentPatternPositions();
430 size_t numAlign = alignPatPos.size();
431 for (size_t i = 0; i < numAlign; i++) {
432 for (size_t j = 0; j < numAlign; j++) {
433 // Don't draw on the three finder corners
434 if (!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0)))
435 drawAlignmentPattern(alignPatPos.at(i), alignPatPos.at(j));
439 // Draw configuration data
440 drawFormatBits(0); // Dummy mask value; overwritten later in the constructor
445 void QrCode::drawFormatBits(int msk) {
446 // Calculate error correction code and pack bits
447 int data = getFormatBits(errorCorrectionLevel) << 3 | msk; // errCorrLvl is uint2, msk is uint3
449 for (int i = 0; i < 10; i++)
450 rem = (rem << 1) ^ ((rem >> 9) * 0x537);
451 int bits = (data << 10 | rem) ^ 0x5412; // uint15
453 throw std::logic_error("Assertion error");
456 for (int i = 0; i <= 5; i++)
457 setFunctionModule(8, i, getBit(bits, i));
458 setFunctionModule(8, 7, getBit(bits, 6));
459 setFunctionModule(8, 8, getBit(bits, 7));
460 setFunctionModule(7, 8, getBit(bits, 8));
461 for (int i = 9; i < 15; i++)
462 setFunctionModule(14 - i, 8, getBit(bits, i));
465 for (int i = 0; i < 8; i++)
466 setFunctionModule(size - 1 - i, 8, getBit(bits, i));
467 for (int i = 8; i < 15; i++)
468 setFunctionModule(8, size - 15 + i, getBit(bits, i));
469 setFunctionModule(8, size - 8, true); // Always black
473 void QrCode::drawVersion() {
477 // Calculate error correction code and pack bits
478 int rem = version; // version is uint6, in the range [7, 40]
479 for (int i = 0; i < 12; i++)
480 rem = (rem << 1) ^ ((rem >> 11) * 0x1F25);
481 long bits = static_cast<long>(version) << 12 | rem; // uint18
483 throw std::logic_error("Assertion error");
486 for (int i = 0; i < 18; i++) {
487 bool bit = getBit(bits, i);
488 int a = size - 11 + i % 3;
490 setFunctionModule(a, b, bit);
491 setFunctionModule(b, a, bit);
496 void QrCode::drawFinderPattern(int x, int y) {
497 for (int dy = -4; dy <= 4; dy++) {
498 for (int dx = -4; dx <= 4; dx++) {
499 int dist = std::max(std::abs(dx), std::abs(dy)); // Chebyshev/infinity norm
500 int xx = x + dx, yy = y + dy;
501 if (0 <= xx && xx < size && 0 <= yy && yy < size)
502 setFunctionModule(xx, yy, dist != 2 && dist != 4);
508 void QrCode::drawAlignmentPattern(int x, int y) {
509 for (int dy = -2; dy <= 2; dy++) {
510 for (int dx = -2; dx <= 2; dx++)
511 setFunctionModule(x + dx, y + dy, std::max(std::abs(dx), std::abs(dy)) != 1);
516 void QrCode::setFunctionModule(int x, int y, bool isBlack) {
517 size_t ux = static_cast<size_t>(x);
518 size_t uy = static_cast<size_t>(y);
519 modules .at(uy).at(ux) = isBlack;
520 isFunction.at(uy).at(ux) = true;
524 bool QrCode::module(int x, int y) const {
525 return modules.at(static_cast<size_t>(y)).at(static_cast<size_t>(x));
529 vector<uint8_t> QrCode::addEccAndInterleave(const vector<uint8_t> &data) const {
530 if (data.size() != static_cast<unsigned int>(getNumDataCodewords(version, errorCorrectionLevel)))
531 throw std::invalid_argument("Invalid argument");
533 // Calculate parameter numbers
534 int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[static_cast<int>(errorCorrectionLevel)][version];
535 int blockEccLen = ECC_CODEWORDS_PER_BLOCK [static_cast<int>(errorCorrectionLevel)][version];
536 int rawCodewords = getNumRawDataModules(version) / 8;
537 int numShortBlocks = numBlocks - rawCodewords % numBlocks;
538 int shortBlockLen = rawCodewords / numBlocks;
540 // Split data into blocks and append ECC to each block
541 vector<vector<uint8_t> > blocks;
542 const vector<uint8_t> rsDiv = reedSolomonComputeDivisor(blockEccLen);
543 for (int i = 0, k = 0; i < numBlocks; i++) {
544 vector<uint8_t> dat(data.cbegin() + k, data.cbegin() + (k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1)));
545 k += static_cast<int>(dat.size());
546 const vector<uint8_t> ecc = reedSolomonComputeRemainder(dat, rsDiv);
547 if (i < numShortBlocks)
549 dat.insert(dat.end(), ecc.cbegin(), ecc.cend());
550 blocks.push_back(std::move(dat));
553 // Interleave (not concatenate) the bytes from every block into a single sequence
554 vector<uint8_t> result;
555 for (size_t i = 0; i < blocks.at(0).size(); i++) {
556 for (size_t j = 0; j < blocks.size(); j++) {
557 // Skip the padding byte in short blocks
558 if (i != static_cast<unsigned int>(shortBlockLen - blockEccLen) || j >= static_cast<unsigned int>(numShortBlocks))
559 result.push_back(blocks.at(j).at(i));
562 if (result.size() != static_cast<unsigned int>(rawCodewords))
563 throw std::logic_error("Assertion error");
568 void QrCode::drawCodewords(const vector<uint8_t> &data) {
569 if (data.size() != static_cast<unsigned int>(getNumRawDataModules(version) / 8))
570 throw std::invalid_argument("Invalid argument");
572 size_t i = 0; // Bit index into the data
573 // Do the funny zigzag scan
574 for (int right = size - 1; right >= 1; right -= 2) { // Index of right column in each column pair
577 for (int vert = 0; vert < size; vert++) { // Vertical counter
578 for (int j = 0; j < 2; j++) {
579 size_t x = static_cast<size_t>(right - j); // Actual x coordinate
580 bool upward = ((right + 1) & 2) == 0;
581 size_t y = static_cast<size_t>(upward ? size - 1 - vert : vert); // Actual y coordinate
582 if (!isFunction.at(y).at(x) && i < data.size() * 8) {
583 modules.at(y).at(x) = getBit(data.at(i >> 3), 7 - static_cast<int>(i & 7));
586 // If this QR Code has any remainder bits (0 to 7), they were assigned as
587 // 0/false/white by the constructor and are left unchanged by this method
591 if (i != data.size() * 8)
592 throw std::logic_error("Assertion error");
596 void QrCode::applyMask(int msk) {
597 if (msk < 0 || msk > 7)
598 throw std::domain_error("Mask value out of range");
599 size_t sz = static_cast<size_t>(size);
600 for (size_t y = 0; y < sz; y++) {
601 for (size_t x = 0; x < sz; x++) {
604 case 0: invert = (x + y) % 2 == 0; break;
605 case 1: invert = y % 2 == 0; break;
606 case 2: invert = x % 3 == 0; break;
607 case 3: invert = (x + y) % 3 == 0; break;
608 case 4: invert = (x / 3 + y / 2) % 2 == 0; break;
609 case 5: invert = x * y % 2 + x * y % 3 == 0; break;
610 case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break;
611 case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break;
612 default: throw std::logic_error("Assertion error");
614 modules.at(y).at(x) = modules.at(y).at(x) ^ (invert & !isFunction.at(y).at(x));
620 long QrCode::getPenaltyScore() const {
623 // Adjacent modules in row having same color, and finder-like patterns
624 for (int y = 0; y < size; y++) {
625 bool runColor = false;
627 std::array<int,7> runHistory = {};
628 for (int x = 0; x < size; x++) {
629 if (module(x, y) == runColor) {
632 result += PENALTY_N1;
636 finderPenaltyAddHistory(runX, runHistory);
638 result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3;
639 runColor = module(x, y);
643 result += finderPenaltyTerminateAndCount(runColor, runX, runHistory) * PENALTY_N3;
645 // Adjacent modules in column having same color, and finder-like patterns
646 for (int x = 0; x < size; x++) {
647 bool runColor = false;
649 std::array<int,7> runHistory = {};
650 for (int y = 0; y < size; y++) {
651 if (module(x, y) == runColor) {
654 result += PENALTY_N1;
658 finderPenaltyAddHistory(runY, runHistory);
660 result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3;
661 runColor = module(x, y);
665 result += finderPenaltyTerminateAndCount(runColor, runY, runHistory) * PENALTY_N3;
668 // 2*2 blocks of modules having same color
669 for (int y = 0; y < size - 1; y++) {
670 for (int x = 0; x < size - 1; x++) {
671 bool color = module(x, y);
672 if ( color == module(x + 1, y) &&
673 color == module(x, y + 1) &&
674 color == module(x + 1, y + 1))
675 result += PENALTY_N2;
679 // Balance of black and white modules
681 for (const vector<bool> &row : modules) {
682 for (bool color : row) {
687 int total = size * size; // Note that size is odd, so black/total != 1/2
688 // Compute the smallest integer k >= 0 such that (45-5k)% <= black/total <= (55+5k)%
689 int k = static_cast<int>((std::abs(black * 20L - total * 10L) + total - 1) / total) - 1;
690 result += k * PENALTY_N4;
695 vector<int> QrCode::getAlignmentPatternPositions() const {
697 return vector<int>();
699 int numAlign = version / 7 + 2;
700 int step = (version == 32) ? 26 :
701 (version*4 + numAlign*2 + 1) / (numAlign*2 - 2) * 2;
703 for (int i = 0, pos = size - 7; i < numAlign - 1; i++, pos -= step)
704 result.insert(result.begin(), pos);
705 result.insert(result.begin(), 6);
711 int QrCode::getNumRawDataModules(int ver) {
712 if (ver < MIN_VERSION || ver > MAX_VERSION)
713 throw std::domain_error("Version number out of range");
714 int result = (16 * ver + 128) * ver + 64;
716 int numAlign = ver / 7 + 2;
717 result -= (25 * numAlign - 10) * numAlign - 55;
721 if (!(208 <= result && result <= 29648))
722 throw std::logic_error("Assertion error");
727 int QrCode::getNumDataCodewords(int ver, Ecc ecl) {
728 return getNumRawDataModules(ver) / 8
729 - ECC_CODEWORDS_PER_BLOCK [static_cast<int>(ecl)][ver]
730 * NUM_ERROR_CORRECTION_BLOCKS[static_cast<int>(ecl)][ver];
734 vector<uint8_t> QrCode::reedSolomonComputeDivisor(int degree) {
735 if (degree < 1 || degree > 255)
736 throw std::domain_error("Degree out of range");
737 // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.
738 // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array {255, 8, 93}.
739 vector<uint8_t> result(static_cast<size_t>(degree));
740 result.at(result.size() - 1) = 1; // Start off with the monomial x^0
742 // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
743 // and drop the highest monomial term which is always 1x^degree.
744 // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
746 for (int i = 0; i < degree; i++) {
747 // Multiply the current product by (x - r^i)
748 for (size_t j = 0; j < result.size(); j++) {
749 result.at(j) = reedSolomonMultiply(result.at(j), root);
750 if (j + 1 < result.size())
751 result.at(j) ^= result.at(j + 1);
753 root = reedSolomonMultiply(root, 0x02);
759 vector<uint8_t> QrCode::reedSolomonComputeRemainder(const vector<uint8_t> &data, const vector<uint8_t> &divisor) {
760 vector<uint8_t> result(divisor.size());
761 for (uint8_t b : data) { // Polynomial division
762 uint8_t factor = b ^ result.at(0);
763 result.erase(result.begin());
765 for (size_t i = 0; i < result.size(); i++)
766 result.at(i) ^= reedSolomonMultiply(divisor.at(i), factor);
772 uint8_t QrCode::reedSolomonMultiply(uint8_t x, uint8_t y) {
773 // Russian peasant multiplication
775 for (int i = 7; i >= 0; i--) {
776 z = (z << 1) ^ ((z >> 7) * 0x11D);
777 z ^= ((y >> i) & 1) * x;
780 throw std::logic_error("Assertion error");
781 return static_cast<uint8_t>(z);
785 int QrCode::finderPenaltyCountPatterns(const std::array<int,7> &runHistory) const {
786 int n = runHistory.at(1);
788 throw std::logic_error("Assertion error");
789 bool core = n > 0 && runHistory.at(2) == n && runHistory.at(3) == n * 3 && runHistory.at(4) == n && runHistory.at(5) == n;
790 return (core && runHistory.at(0) >= n * 4 && runHistory.at(6) >= n ? 1 : 0)
791 + (core && runHistory.at(6) >= n * 4 && runHistory.at(0) >= n ? 1 : 0);
795 int QrCode::finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, std::array<int,7> &runHistory) const {
796 if (currentRunColor) { // Terminate black run
797 finderPenaltyAddHistory(currentRunLength, runHistory);
798 currentRunLength = 0;
800 currentRunLength += size; // Add white border to final run
801 finderPenaltyAddHistory(currentRunLength, runHistory);
802 return finderPenaltyCountPatterns(runHistory);
806 void QrCode::finderPenaltyAddHistory(int currentRunLength, std::array<int,7> &runHistory) const {
807 if (runHistory.at(0) == 0)
808 currentRunLength += size; // Add white border to initial run
809 std::copy_backward(runHistory.cbegin(), runHistory.cend() - 1, runHistory.end());
810 runHistory.at(0) = currentRunLength;
814 bool QrCode::getBit(long x, int i) {
815 return ((x >> i) & 1) != 0;
819 /*---- Tables of constants ----*/
821 const int QrCode::PENALTY_N1 = 3;
822 const int QrCode::PENALTY_N2 = 3;
823 const int QrCode::PENALTY_N3 = 40;
824 const int QrCode::PENALTY_N4 = 10;
827 const int8_t QrCode::ECC_CODEWORDS_PER_BLOCK[4][41] = {
828 // Version: (note that index 0 is for padding, and is set to an illegal value)
829 //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
830 {-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Low
831 {-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28}, // Medium
832 {-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Quartile
833 {-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // High
836 const int8_t QrCode::NUM_ERROR_CORRECTION_BLOCKS[4][41] = {
837 // Version: (note that index 0 is for padding, and is set to an illegal value)
838 //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
839 {-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25}, // Low
840 {-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49}, // Medium
841 {-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68}, // Quartile
842 {-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81}, // High
846 data_too_long::data_too_long(const std::string &msg) :
847 std::length_error(msg) {}
851 BitBuffer::BitBuffer()
852 : std::vector<bool>() {}
855 void BitBuffer::appendBits(std::uint32_t val, int len) {
856 if (len < 0 || len > 31 || val >> len != 0)
857 throw std::domain_error("Value out of range");
858 for (int i = len - 1; i >= 0; i--) // Append bit by bit
859 this->push_back(((val >> i) & 1) != 0);