2 * Copyright 2008 ZXing authors
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.google.zxing.qrcode.encoder;
19 import com.google.zxing.common.ByteMatrix;
20 import com.google.zxing.common.ByteArray;
21 import com.google.zxing.common.reedsolomon.GF256;
22 import com.google.zxing.common.reedsolomon.ReedSolomonEncoder;
23 import com.google.zxing.WriterException;
25 import java.util.Vector;
28 * @author satorux@google.com (Satoru Takabayashi) - creator
29 * @author dswitkin@google.com (Daniel Switkin) - ported from C++
31 public final class Encoder {
33 // The original table is defined in the table 5 of JISX0510:2004 (p.19).
34 private static final int kAlphanumericTable[] = {
35 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x00-0x0f
36 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x10-0x1f
37 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, // 0x20-0x2f
38 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, // 0x30-0x3f
39 -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 0x40-0x4f
40 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, // 0x50-0x5f
43 private static final class RSBlockInfo {
46 final int[][] block_info;
48 public RSBlockInfo(int num_bytes, int[][] block_info) {
49 this.num_bytes = num_bytes;
50 this.block_info = block_info;
55 // The table is from table 12 of JISX0510:2004 (p. 30). The "block_info" parts are ordered by
56 // L, M, Q, H. Within each block_info, the 0th element is num_ec_bytes, and the 1st element is
57 // num_rs_blocks. The table was doublechecked by komatsu.
58 private static final RSBlockInfo kRSBlockTable[] = {
59 new RSBlockInfo( 26, new int[][]{ { 7, 1}, { 10, 1}, { 13, 1}, { 17, 1}}), // Version 1
60 new RSBlockInfo( 44, new int[][]{ { 10, 1}, { 16, 1}, { 22, 1}, { 28, 1}}), // Version 2
61 new RSBlockInfo( 70, new int[][]{ { 15, 1}, { 26, 1}, { 36, 2}, { 44, 2}}), // Version 3
62 new RSBlockInfo( 100, new int[][]{ { 20, 1}, { 36, 2}, { 52, 2}, { 64, 4}}), // Version 4
63 new RSBlockInfo( 134, new int[][]{ { 26, 1}, { 48, 2}, { 72, 4}, { 88, 4}}), // Version 5
64 new RSBlockInfo( 172, new int[][]{ { 36, 2}, { 64, 4}, { 96, 4}, { 112, 4}}), // Version 6
65 new RSBlockInfo( 196, new int[][]{ { 40, 2}, { 72, 4}, { 108, 6}, { 130, 5}}), // Version 7
66 new RSBlockInfo( 242, new int[][]{ { 48, 2}, { 88, 4}, { 132, 6}, { 156, 6}}), // Version 8
67 new RSBlockInfo( 292, new int[][]{ { 60, 2}, { 110, 5}, { 160, 8}, { 192, 8}}), // Version 9
68 new RSBlockInfo( 346, new int[][]{ { 72, 4}, { 130, 5}, { 192, 8}, { 224, 8}}), // Version 10
69 new RSBlockInfo( 404, new int[][]{ { 80, 4}, { 150, 5}, { 224, 8}, { 264, 11}}), // Version 11
70 new RSBlockInfo( 466, new int[][]{ { 96, 4}, { 176, 8}, { 260, 10}, { 308, 11}}), // Version 12
71 new RSBlockInfo( 532, new int[][]{ {104, 4}, { 198, 9}, { 288, 12}, { 352, 16}}), // Version 13
72 new RSBlockInfo( 581, new int[][]{ {120, 4}, { 216, 9}, { 320, 16}, { 384, 16}}), // Version 14
73 new RSBlockInfo( 655, new int[][]{ {132, 6}, { 240, 10}, { 360, 12}, { 432, 18}}), // Version 15
74 new RSBlockInfo( 733, new int[][]{ {144, 6}, { 280, 10}, { 408, 17}, { 480, 16}}), // Version 16
75 new RSBlockInfo( 815, new int[][]{ {168, 6}, { 308, 11}, { 448, 16}, { 532, 19}}), // Version 17
76 new RSBlockInfo( 901, new int[][]{ {180, 6}, { 338, 13}, { 504, 18}, { 588, 21}}), // Version 18
77 new RSBlockInfo( 991, new int[][]{ {196, 7}, { 364, 14}, { 546, 21}, { 650, 25}}), // Version 19
78 new RSBlockInfo(1085, new int[][]{ {224, 8}, { 416, 16}, { 600, 20}, { 700, 25}}), // Version 20
79 new RSBlockInfo(1156, new int[][]{ {224, 8}, { 442, 17}, { 644, 23}, { 750, 25}}), // Version 21
80 new RSBlockInfo(1258, new int[][]{ {252, 9}, { 476, 17}, { 690, 23}, { 816, 34}}), // Version 22
81 new RSBlockInfo(1364, new int[][]{ {270, 9}, { 504, 18}, { 750, 25}, { 900, 30}}), // Version 23
82 new RSBlockInfo(1474, new int[][]{ {300, 10}, { 560, 20}, { 810, 27}, { 960, 32}}), // Version 24
83 new RSBlockInfo(1588, new int[][]{ {312, 12}, { 588, 21}, { 870, 29}, {1050, 35}}), // Version 25
84 new RSBlockInfo(1706, new int[][]{ {336, 12}, { 644, 23}, { 952, 34}, {1110, 37}}), // Version 26
85 new RSBlockInfo(1828, new int[][]{ {360, 12}, { 700, 25}, {1020, 34}, {1200, 40}}), // Version 27
86 new RSBlockInfo(1921, new int[][]{ {390, 13}, { 728, 26}, {1050, 35}, {1260, 42}}), // Version 28
87 new RSBlockInfo(2051, new int[][]{ {420, 14}, { 784, 28}, {1140, 38}, {1350, 45}}), // Version 29
88 new RSBlockInfo(2185, new int[][]{ {450, 15}, { 812, 29}, {1200, 40}, {1440, 48}}), // Version 30
89 new RSBlockInfo(2323, new int[][]{ {480, 16}, { 868, 31}, {1290, 43}, {1530, 51}}), // Version 31
90 new RSBlockInfo(2465, new int[][]{ {510, 17}, { 924, 33}, {1350, 45}, {1620, 54}}), // Version 32
91 new RSBlockInfo(2611, new int[][]{ {540, 18}, { 980, 35}, {1440, 48}, {1710, 57}}), // Version 33
92 new RSBlockInfo(2761, new int[][]{ {570, 19}, {1036, 37}, {1530, 51}, {1800, 60}}), // Version 34
93 new RSBlockInfo(2876, new int[][]{ {570, 19}, {1064, 38}, {1590, 53}, {1890, 63}}), // Version 35
94 new RSBlockInfo(3034, new int[][]{ {600, 20}, {1120, 40}, {1680, 56}, {1980, 66}}), // Version 36
95 new RSBlockInfo(3196, new int[][]{ {630, 21}, {1204, 43}, {1770, 59}, {2100, 70}}), // Version 37
96 new RSBlockInfo(3362, new int[][]{ {660, 22}, {1260, 45}, {1860, 62}, {2220, 74}}), // Version 38
97 new RSBlockInfo(3532, new int[][]{ {720, 24}, {1316, 47}, {1950, 65}, {2310, 77}}), // Version 39
98 new RSBlockInfo(3706, new int[][]{ {750, 25}, {1372, 49}, {2040, 68}, {2430, 81}}), // Version 40
101 private static final class BlockPair {
103 private final ByteArray dataBytes;
104 private final ByteArray errorCorrectionBytes;
106 public BlockPair(ByteArray data, ByteArray errorCorrection) {
108 errorCorrectionBytes = errorCorrection;
111 public ByteArray getDataBytes() {
115 public ByteArray getErrorCorrectionBytes() {
116 return errorCorrectionBytes;
121 // Encode "bytes" with the error correction level "ec_level". The encoding mode will be chosen
122 // internally by ChooseMode(). On success, store the result in "qr_code" and return true. On
123 // error, return false. We recommend you to use QRCode.EC_LEVEL_L (the lowest level) for
124 // "ec_level" since our primary use is to show QR code on desktop screens. We don't need very
125 // strong error correction for this purpose.
127 // Note that there is no way to encode bytes in MODE_KANJI. We might want to add EncodeWithMode()
128 // with which clients can specify the encoding mode. For now, we don't need the functionality.
129 public static void Encode(final ByteArray bytes, int ec_level, QRCode qr_code) throws WriterException {
130 // Step 1: Choose the mode (encoding).
131 final int mode = ChooseMode(bytes);
133 // Step 2: Append "bytes" into "data_bits" in appropriate encoding.
134 BitVector data_bits = new BitVector();
135 AppendBytes(bytes, mode, data_bits);
136 // Step 3: Initialize QR code that can contain "data_bits".
137 final int num_input_bytes = data_bits.num_bytes();
138 InitQRCode(num_input_bytes, ec_level, mode, qr_code);
140 // Step 4: Build another bit vector that contains header and data.
141 BitVector header_and_data_bits = new BitVector();
142 AppendModeInfo(qr_code.mode(), header_and_data_bits);
143 AppendLengthInfo(bytes.size(), qr_code.version(), qr_code.mode(), header_and_data_bits);
144 header_and_data_bits.AppendBitVector(data_bits);
146 // Step 5: Terminate the bits properly.
147 TerminateBits(qr_code.num_data_bytes(), header_and_data_bits);
149 // Step 6: Interleave data bits with error correction code.
150 BitVector final_bits = new BitVector();
151 InterleaveWithECBytes(header_and_data_bits, qr_code.num_total_bytes(), qr_code.num_data_bytes(),
152 qr_code.num_rs_blocks(), final_bits);
154 // Step 7: Choose the mask pattern and set to "qr_code".
155 ByteMatrix matrix = new ByteMatrix(qr_code.matrix_width(), qr_code.matrix_width());
156 qr_code.set_mask_pattern(ChooseMaskPattern(final_bits, qr_code.ec_level(), qr_code.version(),
159 // Step 8. Build the matrix and set it to "qr_code".
160 MatrixUtil.BuildMatrix(final_bits, qr_code.ec_level(), qr_code.version(),
161 qr_code.mask_pattern(), matrix);
162 qr_code.set_matrix(matrix);
163 // Step 9. Make sure we have a valid QR Code.
164 if (!qr_code.IsValid()) {
165 throw new WriterException("Invalid QR code: " + qr_code.toString());
169 // Return the code point of the table used in alphanumeric mode. Return -1 if there is no
170 // corresponding code in the table.
171 static int GetAlphanumericCode(int code) {
172 if (code < kAlphanumericTable.length) {
173 return kAlphanumericTable[code];
178 // Choose the best mode by examining the content of "bytes". The function is guaranteed to return
181 // Note that this function does not return MODE_KANJI, as we cannot distinguish Shift_JIS from
182 // other encodings such as ISO-8859-1, from data bytes alone. For example "\xE0\xE0" can be
183 // interpreted as one character in Shift_JIS, but also two characters in ISO-8859-1.
185 // JAVAPORT: This MODE_KANJI limitation sounds like a problem for us.
186 public static int ChooseMode(final ByteArray bytes) throws WriterException {
187 boolean has_numeric = false;
188 boolean has_alphanumeric = false;
189 boolean has_other = false;
190 for (int i = 0; i < bytes.size(); ++i) {
191 final int oneByte = bytes.at(i);
192 if (oneByte >= '0' && oneByte <= '9') {
194 } else if (GetAlphanumericCode(oneByte) != -1) {
195 has_alphanumeric = true;
201 return QRCode.MODE_8BIT_BYTE;
202 } else if (has_alphanumeric) {
203 return QRCode.MODE_ALPHANUMERIC;
204 } else if (has_numeric) {
205 return QRCode.MODE_NUMERIC;
207 // "bytes" must be empty to reach here.
208 if (!bytes.empty()) {
209 throw new WriterException("Bytes left over");
211 return QRCode.MODE_8BIT_BYTE;
214 private static int ChooseMaskPattern(final BitVector bits, int ec_level, int version,
215 ByteMatrix matrix) throws WriterException {
216 if (!QRCode.IsValidMatrixWidth(matrix.width())) {
217 throw new WriterException("Invalid matrix width: " + matrix.width());
220 int min_penalty = Integer.MAX_VALUE; // Lower penalty is better.
221 int best_mask_pattern = -1;
222 // We try all mask patterns to choose the best one.
223 for (int i = 0; i < QRCode.kNumMaskPatterns; ++i) {
224 final int mask_pattern = i;
225 MatrixUtil.BuildMatrix(bits, ec_level, version, mask_pattern, matrix);
226 final int penalty = MaskUtil.CalculateMaskPenalty(matrix);
227 System.out.println("mask_pattern: " + mask_pattern + ", " + "penalty: " + penalty);
228 if (penalty < min_penalty) {
229 min_penalty = penalty;
230 best_mask_pattern = mask_pattern;
233 return best_mask_pattern;
236 // Initialize "qr_code" according to "num_input_bytes", "ec_level", and "mode". On success, modify
237 // "qr_code" and return true. On error, return false.
238 private static void InitQRCode(int num_input_bytes, int ec_level, int mode, QRCode qr_code) throws WriterException {
239 qr_code.set_ec_level(ec_level);
240 qr_code.set_mode(mode);
242 if (!QRCode.IsValidECLevel(ec_level)) {
243 throw new WriterException("Invalid EC level: " + ec_level);
246 // In the following comments, we use numbers of Version 7-H.
247 for (int i = 0; i < kRSBlockTable.length; ++i) {
248 final RSBlockInfo row = kRSBlockTable[i];
250 final int num_bytes = row.num_bytes;
251 // num_ec_bytes = 130
252 final int num_ec_bytes = row.block_info[ec_level][0];
254 final int num_rs_blocks = row.block_info[ec_level][1];
255 // num_data_bytes = 196 - 130 = 66
256 final int num_data_bytes = num_bytes - num_ec_bytes;
257 // We want to choose the smallest version which can contain data of "num_input_bytes" + some
258 // extra bits for the header (mode info and length info). The header can be three bytes
259 // (precisely 4 + 16 bits) at most. Hence we do +3 here.
260 if (num_data_bytes >= num_input_bytes + 3) {
261 // Yay, we found the proper rs block info!
262 qr_code.set_version(i + 1);
263 qr_code.set_num_total_bytes(num_bytes);
264 qr_code.set_num_data_bytes(num_data_bytes);
265 qr_code.set_num_rs_blocks(num_rs_blocks);
266 // num_ec_bytes = 196 - 66 = 130
267 qr_code.set_num_ec_bytes(num_bytes - num_data_bytes);
268 // num_matrix_width = 21 + 6 * 4 = 45
269 qr_code.set_matrix_width(21 + i * 4);
273 throw new WriterException("Cannot find proper rs block info (input data too big?)");
276 // Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).
277 static void TerminateBits(int num_data_bytes, BitVector bits) throws WriterException {
278 final int capacity = num_data_bytes * 8;
279 if (bits.size() > capacity) {
280 throw new WriterException("data bits cannot fit in the QR Code" + bits.size() + " > " + capacity);
282 // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details.
283 for (int i = 0; i < 4 && bits.size() < capacity; ++i) {
286 final int num_bits_in_last_byte = bits.size() % 8;
287 // If the last byte isn't 8-bit aligned, we'll add padding bits.
288 if (num_bits_in_last_byte > 0) {
289 final int num_padding_bits = 8 - num_bits_in_last_byte;
290 for (int i = 0; i < num_padding_bits; ++i) {
294 // Should be 8-bit aligned here.
295 if (bits.size() % 8 != 0) {
296 throw new WriterException("Number of bits is not a multiple of 8");
298 // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24).
299 final int num_padding_bytes = num_data_bytes - bits.num_bytes();
300 for (int i = 0; i < num_padding_bytes; ++i) {
302 bits.AppendBits(0xec, 8);
304 bits.AppendBits(0x11, 8);
307 if (bits.size() != capacity) {
308 throw new WriterException("Bits size does not equal capacity");
312 // Get number of data bytes and number of error correction bytes for block id "block_id". Store
313 // the result in "num_data_bytes_in_block", and "num_ec_bytes_in_block". See table 12 in 8.5.1 of
314 // JISX0510:2004 (p.30)
315 static void GetNumDataBytesAndNumECBytesForBlockID(int num_total_bytes, int num_data_bytes,
316 int num_rs_blocks, int block_id, int[] num_data_bytes_in_block,
317 int[] num_ec_bytes_in_block) throws WriterException {
318 if (block_id >= num_rs_blocks) {
319 throw new WriterException("Block ID too large");
321 // num_rs_blocks_in_group2 = 196 % 5 = 1
322 final int num_rs_blocks_in_group2 = num_total_bytes % num_rs_blocks;
323 // num_rs_blocks_in_group1 = 5 - 1 = 4
324 final int num_rs_blocks_in_group1 = num_rs_blocks - num_rs_blocks_in_group2;
325 // num_total_bytes_in_group1 = 196 / 5 = 39
326 final int num_total_bytes_in_group1 = num_total_bytes / num_rs_blocks;
327 // num_total_bytes_in_group2 = 39 + 1 = 40
328 final int num_total_bytes_in_group2 = num_total_bytes_in_group1 + 1;
329 // num_data_bytes_in_group1 = 66 / 5 = 13
330 final int num_data_bytes_in_group1 = num_data_bytes / num_rs_blocks;
331 // num_data_bytes_in_group2 = 13 + 1 = 14
332 final int num_data_bytes_in_group2 = num_data_bytes_in_group1 + 1;
333 // num_ec_bytes_in_group1 = 39 - 13 = 26
334 final int num_ec_bytes_in_group1 = num_total_bytes_in_group1 -
335 num_data_bytes_in_group1;
336 // num_ec_bytes_in_group2 = 40 - 14 = 26
337 final int num_ec_bytes_in_group2 = num_total_bytes_in_group2 -
338 num_data_bytes_in_group2;
341 if (num_ec_bytes_in_group1 != num_ec_bytes_in_group2) {
342 throw new WriterException("EC bytes mismatch");
345 if (num_rs_blocks != num_rs_blocks_in_group1 + num_rs_blocks_in_group2) {
346 throw new WriterException("RS blocks mismatch");
348 // 196 = (13 + 26) * 4 + (14 + 26) * 1
349 if (num_total_bytes !=
350 ((num_data_bytes_in_group1 + num_ec_bytes_in_group1) *
351 num_rs_blocks_in_group1) +
352 ((num_data_bytes_in_group2 + num_ec_bytes_in_group2) *
353 num_rs_blocks_in_group2)) {
354 throw new WriterException("Total bytes mismatch");
357 if (block_id < num_rs_blocks_in_group1) {
358 num_data_bytes_in_block[0] = num_data_bytes_in_group1;
359 num_ec_bytes_in_block[0] = num_ec_bytes_in_group1;
361 num_data_bytes_in_block[0] = num_data_bytes_in_group2;
362 num_ec_bytes_in_block[0] = num_ec_bytes_in_group2;
366 // Interleave "bits" with corresponding error correction bytes. On success, store the result in
367 // "result" and return true. On error, return false. The interleave rule is complicated. See 8.6
368 // of JISX0510:2004 (p.37) for details.
369 static void InterleaveWithECBytes(final BitVector bits, int num_total_bytes,
370 int num_data_bytes, int num_rs_blocks, BitVector result) throws WriterException {
372 // "bits" must have "num_data_bytes" bytes of data.
373 if (bits.num_bytes() != num_data_bytes) {
374 throw new WriterException("Number of bits and data bytes does not match");
377 // Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll
378 // store the divided data bytes blocks and error correction bytes blocks into "blocks".
379 int data_bytes_offset = 0;
380 int max_num_data_bytes = 0;
381 int max_num_ec_bytes = 0;
383 // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number.
384 Vector blocks = new Vector(num_rs_blocks);
386 for (int i = 0; i < num_rs_blocks; ++i) {
387 int[] num_data_bytes_in_block = new int[1];
388 int[] num_ec_bytes_in_block = new int[1];
389 GetNumDataBytesAndNumECBytesForBlockID(
390 num_total_bytes, num_data_bytes, num_rs_blocks, i,
391 num_data_bytes_in_block, num_ec_bytes_in_block);
393 ByteArray data_bytes = new ByteArray();
394 data_bytes.set(bits.getArray(), data_bytes_offset, num_data_bytes_in_block[0]);
395 ByteArray ec_bytes = GenerateECBytes(data_bytes, num_ec_bytes_in_block[0]);
396 blocks.addElement(new BlockPair(data_bytes, ec_bytes));
398 max_num_data_bytes = Math.max(max_num_data_bytes, data_bytes.size());
399 max_num_ec_bytes = Math.max(max_num_ec_bytes, ec_bytes.size());
400 data_bytes_offset += num_data_bytes_in_block[0];
402 if (num_data_bytes != data_bytes_offset) {
403 throw new WriterException("Data bytes does not match offset");
406 // First, place data blocks.
407 for (int i = 0; i < max_num_data_bytes; ++i) {
408 for (int j = 0; j < blocks.size(); ++j) {
409 final ByteArray data_bytes = ((BlockPair) blocks.elementAt(j)).getDataBytes();
410 if (i < data_bytes.size()) {
411 result.AppendBits(data_bytes.at(i), 8);
415 // Then, place error correction blocks.
416 for (int i = 0; i < max_num_ec_bytes; ++i) {
417 for (int j = 0; j < blocks.size(); ++j) {
418 final ByteArray ec_bytes = ((BlockPair) blocks.elementAt(j)).getErrorCorrectionBytes();
419 if (i < ec_bytes.size()) {
420 result.AppendBits(ec_bytes.at(i), 8);
424 if (num_total_bytes != result.num_bytes()) { // Should be same.
425 throw new WriterException("Interleaving error: " + num_total_bytes + " and " + result.num_bytes() +
430 static ByteArray GenerateECBytes(ByteArray data_bytes, int num_ec_bytes_in_block) {
431 int numDataBytes = data_bytes.size();
432 int[] toEncode = new int[numDataBytes + num_ec_bytes_in_block];
433 for (int i = 0; i < numDataBytes; i++) {
434 toEncode[i] = data_bytes.at(i);
436 new ReedSolomonEncoder(GF256.QR_CODE_FIELD).encode(toEncode, num_ec_bytes_in_block);
438 ByteArray ec_bytes = new ByteArray(num_ec_bytes_in_block);
439 for (int i = 0; i < num_ec_bytes_in_block; i++) {
440 ec_bytes.set(i, toEncode[numDataBytes + i]);
445 // Append mode info. On success, store the result in "bits" and return true. On error, return
447 static void AppendModeInfo(int mode, BitVector bits) throws WriterException {
448 final int code = QRCode.GetModeCode(mode);
449 bits.AppendBits(code, 4);
453 // Append length info. On success, store the result in "bits" and return true. On error, return
455 static void AppendLengthInfo(int num_bytes, int version, int mode, BitVector bits) throws WriterException {
456 int num_letters = num_bytes;
457 // In Kanji mode, a letter is represented in two bytes.
458 if (mode == QRCode.MODE_KANJI) {
459 if (num_letters % 2 != 0) {
460 throw new WriterException("Number of letters must be even");
465 final int num_bits = QRCode.GetNumBitsForLength(version, mode);
466 if (num_letters > ((1 << num_bits) - 1)) {
467 throw new WriterException(num_letters + "is bigger than" + ((1 << num_bits) - 1));
469 bits.AppendBits(num_letters, num_bits);
472 // Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits"
473 // and return true. On error, return false.
474 static void AppendBytes(final ByteArray bytes, int mode, BitVector bits) throws WriterException {
476 case QRCode.MODE_NUMERIC:
477 AppendNumericBytes(bytes, bits);
479 case QRCode.MODE_ALPHANUMERIC:
480 AppendAlphanumericBytes(bytes, bits);
482 case QRCode.MODE_8BIT_BYTE:
483 Append8BitBytes(bytes, bits);
485 case QRCode.MODE_KANJI:
486 AppendKanjiBytes(bytes, bits);
489 throw new WriterException("Invalid mode: " + mode);
493 // Append "bytes" to "bits" using QRCode.MODE_NUMERIC mode. On success, store the result in "bits"
494 // and return true. On error, return false.
495 static void AppendNumericBytes(final ByteArray bytes, BitVector bits) throws WriterException {
496 // Validate all the bytes first.
497 for (int i = 0; i < bytes.size(); ++i) {
498 int oneByte = bytes.at(i);
499 if (oneByte < '0' || oneByte > '9') {
500 throw new WriterException("Non-digit found");
503 for (int i = 0; i < bytes.size();) {
504 final int num1 = bytes.at(i) - '0';
505 if (i + 2 < bytes.size()) {
506 // Encode three numeric letters in ten bits.
507 final int num2 = bytes.at(i + 1) - '0';
508 final int num3 = bytes.at(i + 2) - '0';
509 bits.AppendBits(num1 * 100 + num2 * 10 + num3, 10);
511 } else if (i + 1 < bytes.size()) {
512 // Encode two numeric letters in seven bits.
513 final int num2 = bytes.at(i + 1) - '0';
514 bits.AppendBits(num1 * 10 + num2, 7);
517 // Encode one numeric letter in four bits.
518 bits.AppendBits(num1, 4);
524 // Append "bytes" to "bits" using QRCode.MODE_ALPHANUMERIC mode. On success, store the result in
525 // "bits" and return true. On error, return false.
526 static void AppendAlphanumericBytes(final ByteArray bytes, BitVector bits) throws WriterException {
527 for (int i = 0; i < bytes.size();) {
528 final int code1 = GetAlphanumericCode(bytes.at(i));
530 throw new WriterException();
532 if (i + 1 < bytes.size()) {
533 final int code2 = GetAlphanumericCode(bytes.at(i + 1));
535 throw new WriterException();
537 // Encode two alphanumeric letters in 11 bits.
538 bits.AppendBits(code1 * 45 + code2, 11);
541 // Encode one alphanumeric letter in six bits.
542 bits.AppendBits(code1, 6);
548 // Append "bytes" to "bits" using QRCode.MODE_8BIT_BYTE mode. On success, store the result in
549 // "bits" and return true. On error, return false.
550 static void Append8BitBytes(final ByteArray bytes, BitVector bits) {
551 for (int i = 0; i < bytes.size(); ++i) {
552 bits.AppendBits(bytes.at(i), 8);
556 // Append "bytes" to "bits" using QRCode.MODE_KANJI mode. On success, store the result in "bits"
557 // and return true. On error, return false. See 8.4.5 of JISX0510:2004 (p.21) for how to encode
559 static void AppendKanjiBytes(final ByteArray bytes, BitVector bits) throws WriterException {
560 if (bytes.size() % 2 != 0) {
561 throw new WriterException("Number of bytes must be even");
563 for (int i = 0; i < bytes.size(); i += 2) {
564 if (!IsValidKanji(bytes.at(i), bytes.at(i + 1))) {
565 throw new WriterException("Invalid Kanji at " + i);
567 final int code = (bytes.at(i) << 8) | bytes.at(i + 1);
569 if (code >= 0x8140 && code <= 0x9ffc) {
570 subtracted = code - 0x8140;
571 } else if (code >= 0xe040 && code <= 0xebbf) {
572 subtracted = code - 0xc140;
574 if (subtracted == -1) {
575 throw new WriterException("Invalid byte sequence: " + bytes);
577 final int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff);
578 bits.AppendBits(encoded, 13);
582 // Check if "byte1" and "byte2" can compose a valid Kanji letter (2-byte Shift_JIS letter). The
583 // numbers are from http://ja.wikipedia.org/wiki/Shift_JIS.
584 static boolean IsValidKanji(final int byte1, final int byte2) {
585 return (byte2 != 0x7f &&
586 ((byte1 >= 0x81 && byte1 <= 0x9f &&
587 byte2 >= 0x40 && byte2 <= 0xfc) ||
588 ((byte1 >= 0xe0 && byte1 <= 0xfc &&
589 byte2 >= 0x40 && byte2 <= 0xfc))));
592 // Check if "bytes" is a valid Kanji sequence. Used by the unit tests.
593 static boolean IsValidKanjiSequence(final ByteArray bytes) {
594 if (bytes.size() % 2 != 0) {
598 for (; i < bytes.size(); i += 2) {
599 if (!IsValidKanji(bytes.at(i), bytes.at(i + 1))) {
603 return i == bytes.size(); // Consumed all bytes?