Encoder.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. /*
  2. * Copyright 2008 ZXing authors
  3. *
  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
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  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.
  15. */
  16. using System;
  17. namespace FastReport.Barcode.QRCode
  18. {
  19. /* /// <author> satorux@google.com (Satoru Takabayashi) - creator
  20. /// </author>
  21. /// <author> dswitkin@google.com (Daniel Switkin) - ported from C++
  22. /// </author>
  23. /// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
  24. /// </author>*/
  25. internal sealed class Encoder
  26. {
  27. // The original table is defined in the table 5 of JISX0510:2004 (p.19).
  28. //UPGRADE_NOTE: Final was removed from the declaration of 'ALPHANUMERIC_TABLE'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
  29. private static readonly int[] ALPHANUMERIC_TABLE = new int[]{- 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, 36, - 1, - 1, - 1, 37, 38, - 1, - 1, - 1, - 1, 39, 40, - 1, 41, 42, 43, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, - 1, - 1, - 1, - 1, - 1, - 1, 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, - 1, - 1, - 1, - 1, - 1};
  30. internal const System.String DEFAULT_BYTE_MODE_ENCODING = "ISO-8859-1";
  31. private Encoder()
  32. {
  33. }
  34. // The mask penalty calculation is complicated. See Table 21 of JISX0510:2004 (p.45) for details.
  35. // Basically it applies four rules and summate all penalties.
  36. private static int calculateMaskPenalty(ByteMatrix matrix)
  37. {
  38. int penalty = 0;
  39. penalty += MaskUtil.applyMaskPenaltyRule1(matrix);
  40. penalty += MaskUtil.applyMaskPenaltyRule2(matrix);
  41. penalty += MaskUtil.applyMaskPenaltyRule3(matrix);
  42. penalty += MaskUtil.applyMaskPenaltyRule4(matrix);
  43. return penalty;
  44. }
  45. /*/// <summary> Encode "bytes" with the error correction level "ecLevel". The encoding mode will be chosen
  46. /// internally by chooseMode(). On success, store the result in "qrCode".
  47. ///
  48. /// We recommend you to use QRCode.EC_LEVEL_L (the lowest level) for
  49. /// "getECLevel" since our primary use is to show QR code on desktop screens. We don't need very
  50. /// strong error correction for this purpose.
  51. ///
  52. /// Note that there is no way to encode bytes in MODE_KANJI. We might want to add EncodeWithMode()
  53. /// with which clients can specify the encoding mode. For now, we don't need the functionality.
  54. /// </summary>*/
  55. public static void encode(System.String content, ErrorCorrectionLevel ecLevel, QRCode qrCode)
  56. {
  57. encode(content, ecLevel, null, qrCode);
  58. }
  59. public static void encode(System.String content, ErrorCorrectionLevel ecLevel, System.String encoding, QRCode qrCode)
  60. {
  61. if (encoding == null)
  62. {
  63. encoding = DEFAULT_BYTE_MODE_ENCODING;
  64. }
  65. // Step 1: Choose the mode (encoding).
  66. Mode mode = chooseMode(content, encoding);
  67. // Step 2: Append "bytes" into "dataBits" in appropriate encoding.
  68. BitVector dataBits = new BitVector();
  69. appendBytes(content, mode, dataBits, encoding);
  70. // Step 3: Initialize QR code that can contain "dataBits".
  71. int numInputBytes = dataBits.sizeInBytes();
  72. initQRCode(numInputBytes, ecLevel, mode, qrCode);
  73. // Step 4: Build another bit vector that contains header and data.
  74. BitVector headerAndDataBits = new BitVector();
  75. // tz - commented out to match zxing encoder online
  76. // Step 4.5: Append ECI message if applicable
  77. /*if (mode == Mode.BYTE && !DEFAULT_BYTE_MODE_ENCODING.Equals(encoding))
  78. {
  79. CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding);
  80. if (eci != null)
  81. {
  82. appendECI(eci, headerAndDataBits);
  83. }
  84. }*/
  85. appendModeInfo(mode, headerAndDataBits);
  86. int numLetters = mode.Equals(Mode.BYTE)?dataBits.sizeInBytes():content.Length;
  87. appendLengthInfo(numLetters, qrCode.Version, mode, headerAndDataBits);
  88. headerAndDataBits.appendBitVector(dataBits);
  89. // Step 5: Terminate the bits properly.
  90. terminateBits(qrCode.NumDataBytes, headerAndDataBits);
  91. // Step 6: Interleave data bits with error correction code.
  92. BitVector finalBits = new BitVector();
  93. interleaveWithECBytes(headerAndDataBits, qrCode.NumTotalBytes, qrCode.NumDataBytes, qrCode.NumRSBlocks, finalBits);
  94. // Step 7: Choose the mask pattern and set to "qrCode".
  95. ByteMatrix matrix = new ByteMatrix(qrCode.MatrixWidth, qrCode.MatrixWidth);
  96. qrCode.MaskPattern = chooseMaskPattern(finalBits, qrCode.ECLevel, qrCode.Version, matrix);
  97. // Step 8. Build the matrix and set it to "qrCode".
  98. MatrixUtil.buildMatrix(finalBits, qrCode.ECLevel, qrCode.Version, qrCode.MaskPattern, matrix);
  99. qrCode.Matrix = matrix;
  100. // Step 9. Make sure we have a valid QR Code.
  101. if (!qrCode.Valid)
  102. {
  103. throw new WriterException("Invalid QR code: " + qrCode.ToString());
  104. }
  105. }
  106. /*/// <returns> the code point of the table used in alphanumeric mode or
  107. /// -1 if there is no corresponding code in the table.
  108. /// </returns>*/
  109. internal static int getAlphanumericCode(int code)
  110. {
  111. if (code < ALPHANUMERIC_TABLE.Length)
  112. {
  113. return ALPHANUMERIC_TABLE[code];
  114. }
  115. return - 1;
  116. }
  117. public static Mode chooseMode(System.String content)
  118. {
  119. return chooseMode(content, null);
  120. }
  121. /*/// <summary> Choose the best mode by examining the content. Note that 'encoding' is used as a hint;
  122. /// if it is Shift_JIS, and the input is only double-byte Kanji, then we return {@link Mode#KANJI}.
  123. /// </summary>*/
  124. public static Mode chooseMode(System.String content, System.String encoding)
  125. {
  126. if ("Shift_JIS".Equals(encoding))
  127. {
  128. // Choose Kanji mode if all input are double-byte characters
  129. return isOnlyDoubleByteKanji(content)?Mode.KANJI:Mode.BYTE;
  130. }
  131. bool hasNumeric = false;
  132. bool hasAlphanumeric = false;
  133. for (int i = 0; i < content.Length; ++i)
  134. {
  135. char c = content[i];
  136. if (c >= '0' && c <= '9')
  137. {
  138. hasNumeric = true;
  139. }
  140. else if (getAlphanumericCode(c) != - 1)
  141. {
  142. hasAlphanumeric = true;
  143. }
  144. else
  145. {
  146. return Mode.BYTE;
  147. }
  148. }
  149. if (hasAlphanumeric)
  150. {
  151. return Mode.ALPHANUMERIC;
  152. }
  153. else if (hasNumeric)
  154. {
  155. return Mode.NUMERIC;
  156. }
  157. return Mode.BYTE;
  158. }
  159. private static bool isOnlyDoubleByteKanji(System.String content)
  160. {
  161. sbyte[] bytes;
  162. try
  163. {
  164. //UPGRADE_TODO: Method 'java.lang.String.getBytes' was converted to 'System.Text.Encoding.GetEncoding(string).GetBytes(string)' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javalangStringgetBytes_javalangString'"
  165. bytes = SupportClass.ToSByteArray(System.Text.Encoding.GetEncoding("Shift_JIS").GetBytes(content));
  166. }
  167. catch
  168. {
  169. return false;
  170. }
  171. int length = bytes.Length;
  172. if (length % 2 != 0)
  173. {
  174. return false;
  175. }
  176. for (int i = 0; i < length; i += 2)
  177. {
  178. int byte1 = bytes[i] & 0xFF;
  179. if ((byte1 < 0x81 || byte1 > 0x9F) && (byte1 < 0xE0 || byte1 > 0xEB))
  180. {
  181. return false;
  182. }
  183. }
  184. return true;
  185. }
  186. private static int chooseMaskPattern(BitVector bits, ErrorCorrectionLevel ecLevel, int version, ByteMatrix matrix)
  187. {
  188. int minPenalty = System.Int32.MaxValue; // Lower penalty is better.
  189. int bestMaskPattern = - 1;
  190. // We try all mask patterns to choose the best one.
  191. for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++)
  192. {
  193. MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix);
  194. int penalty = calculateMaskPenalty(matrix);
  195. if (penalty < minPenalty)
  196. {
  197. minPenalty = penalty;
  198. bestMaskPattern = maskPattern;
  199. }
  200. }
  201. return bestMaskPattern;
  202. }
  203. /*/// <summary> Initialize "qrCode" according to "numInputBytes", "ecLevel", and "mode". On success,
  204. /// modify "qrCode".
  205. /// </summary>*/
  206. private static void initQRCode(int numInputBytes, ErrorCorrectionLevel ecLevel, Mode mode, QRCode qrCode)
  207. {
  208. qrCode.ECLevel = ecLevel;
  209. qrCode.Mode = mode;
  210. // In the following comments, we use numbers of Version 7-H.
  211. for (int versionNum = 1; versionNum <= 40; versionNum++)
  212. {
  213. Version version = Version.getVersionForNumber(versionNum);
  214. // numBytes = 196
  215. int numBytes = version.TotalCodewords;
  216. // getNumECBytes = 130
  217. Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
  218. int numEcBytes = ecBlocks.TotalECCodewords;
  219. // getNumRSBlocks = 5
  220. int numRSBlocks = ecBlocks.NumBlocks;
  221. // getNumDataBytes = 196 - 130 = 66
  222. int numDataBytes = numBytes - numEcBytes;
  223. // We want to choose the smallest version which can contain data of "numInputBytes" + some
  224. // extra bits for the header (mode info and length info). The header can be three bytes
  225. // (precisely 4 + 16 bits) at most. Hence we do +3 here.
  226. if (numDataBytes >= numInputBytes + 3)
  227. {
  228. // Yay, we found the proper rs block info!
  229. qrCode.Version = versionNum;
  230. qrCode.NumTotalBytes = numBytes;
  231. qrCode.NumDataBytes = numDataBytes;
  232. qrCode.NumRSBlocks = numRSBlocks;
  233. // getNumECBytes = 196 - 66 = 130
  234. qrCode.NumECBytes = numEcBytes;
  235. // matrix width = 21 + 6 * 4 = 45
  236. qrCode.MatrixWidth = version.DimensionForVersion;
  237. return ;
  238. }
  239. }
  240. throw new WriterException("Cannot find proper rs block info (input data too big?)");
  241. }
  242. /*/// <summary> Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).</summary>*/
  243. internal static void terminateBits(int numDataBytes, BitVector bits)
  244. {
  245. int capacity = numDataBytes << 3;
  246. if (bits.size() > capacity)
  247. {
  248. throw new WriterException("data bits cannot fit in the QR Code" + bits.size() + " > " + capacity);
  249. }
  250. // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details.
  251. // TODO: srowen says we can remove this for loop, since the 4 terminator bits are optional if
  252. // the last byte has less than 4 bits left. So it amounts to padding the last byte with zeroes
  253. // either way.
  254. for (int i = 0; i < 4 && bits.size() < capacity; ++i)
  255. {
  256. bits.appendBit(0);
  257. }
  258. int numBitsInLastByte = bits.size() % 8;
  259. // If the last byte isn't 8-bit aligned, we'll add padding bits.
  260. if (numBitsInLastByte > 0)
  261. {
  262. int numPaddingBits = 8 - numBitsInLastByte;
  263. for (int i = 0; i < numPaddingBits; ++i)
  264. {
  265. bits.appendBit(0);
  266. }
  267. }
  268. // Should be 8-bit aligned here.
  269. if (bits.size() % 8 != 0)
  270. {
  271. throw new WriterException("Number of bits is not a multiple of 8");
  272. }
  273. // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24).
  274. int numPaddingBytes = numDataBytes - bits.sizeInBytes();
  275. for (int i = 0; i < numPaddingBytes; ++i)
  276. {
  277. if (i % 2 == 0)
  278. {
  279. bits.appendBits(0xec, 8);
  280. }
  281. else
  282. {
  283. bits.appendBits(0x11, 8);
  284. }
  285. }
  286. if (bits.size() != capacity)
  287. {
  288. throw new WriterException("Bits size does not equal capacity");
  289. }
  290. }
  291. /*/// <summary> Get number of data bytes and number of error correction bytes for block id "blockID". Store
  292. /// the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of
  293. /// JISX0510:2004 (p.30)
  294. /// </summary>*/
  295. internal static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes, int numDataBytes, int numRSBlocks, int blockID, int[] numDataBytesInBlock, int[] numECBytesInBlock)
  296. {
  297. if (blockID >= numRSBlocks)
  298. {
  299. throw new WriterException("Block ID too large");
  300. }
  301. // numRsBlocksInGroup2 = 196 % 5 = 1
  302. int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks;
  303. // numRsBlocksInGroup1 = 5 - 1 = 4
  304. int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2;
  305. // numTotalBytesInGroup1 = 196 / 5 = 39
  306. int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks;
  307. // numTotalBytesInGroup2 = 39 + 1 = 40
  308. int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1;
  309. // numDataBytesInGroup1 = 66 / 5 = 13
  310. int numDataBytesInGroup1 = numDataBytes / numRSBlocks;
  311. // numDataBytesInGroup2 = 13 + 1 = 14
  312. int numDataBytesInGroup2 = numDataBytesInGroup1 + 1;
  313. // numEcBytesInGroup1 = 39 - 13 = 26
  314. int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1;
  315. // numEcBytesInGroup2 = 40 - 14 = 26
  316. int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2;
  317. // Sanity checks.
  318. // 26 = 26
  319. if (numEcBytesInGroup1 != numEcBytesInGroup2)
  320. {
  321. throw new WriterException("EC bytes mismatch");
  322. }
  323. // 5 = 4 + 1.
  324. if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2)
  325. {
  326. throw new WriterException("RS blocks mismatch");
  327. }
  328. // 196 = (13 + 26) * 4 + (14 + 26) * 1
  329. if (numTotalBytes != ((numDataBytesInGroup1 + numEcBytesInGroup1) * numRsBlocksInGroup1) + ((numDataBytesInGroup2 + numEcBytesInGroup2) * numRsBlocksInGroup2))
  330. {
  331. throw new WriterException("Total bytes mismatch");
  332. }
  333. if (blockID < numRsBlocksInGroup1)
  334. {
  335. numDataBytesInBlock[0] = numDataBytesInGroup1;
  336. numECBytesInBlock[0] = numEcBytesInGroup1;
  337. }
  338. else
  339. {
  340. numDataBytesInBlock[0] = numDataBytesInGroup2;
  341. numECBytesInBlock[0] = numEcBytesInGroup2;
  342. }
  343. }
  344. /*/// <summary> Interleave "bits" with corresponding error correction bytes. On success, store the result in
  345. /// "result". The interleave rule is complicated. See 8.6 of JISX0510:2004 (p.37) for details.
  346. /// </summary>*/
  347. internal static void interleaveWithECBytes(BitVector bits, int numTotalBytes, int numDataBytes, int numRSBlocks, BitVector result)
  348. {
  349. // "bits" must have "getNumDataBytes" bytes of data.
  350. if (bits.sizeInBytes() != numDataBytes)
  351. {
  352. throw new WriterException("Number of bits and data bytes does not match");
  353. }
  354. // Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll
  355. // store the divided data bytes blocks and error correction bytes blocks into "blocks".
  356. int dataBytesOffset = 0;
  357. int maxNumDataBytes = 0;
  358. int maxNumEcBytes = 0;
  359. // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number.
  360. System.Collections.ArrayList blocks = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(numRSBlocks));
  361. for (int i = 0; i < numRSBlocks; ++i)
  362. {
  363. int[] numDataBytesInBlock = new int[1];
  364. int[] numEcBytesInBlock = new int[1];
  365. getNumDataBytesAndNumECBytesForBlockID(numTotalBytes, numDataBytes, numRSBlocks, i, numDataBytesInBlock, numEcBytesInBlock);
  366. ByteArray dataBytes = new ByteArray();
  367. dataBytes.set_Renamed(bits.Array, dataBytesOffset, numDataBytesInBlock[0]);
  368. ByteArray ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]);
  369. blocks.Add(new BlockPair(dataBytes, ecBytes));
  370. maxNumDataBytes = System.Math.Max(maxNumDataBytes, dataBytes.size());
  371. maxNumEcBytes = System.Math.Max(maxNumEcBytes, ecBytes.size());
  372. dataBytesOffset += numDataBytesInBlock[0];
  373. }
  374. if (numDataBytes != dataBytesOffset)
  375. {
  376. throw new WriterException("Data bytes does not match offset");
  377. }
  378. // First, place data blocks.
  379. for (int i = 0; i < maxNumDataBytes; ++i)
  380. {
  381. for (int j = 0; j < blocks.Count; ++j)
  382. {
  383. ByteArray dataBytes = ((BlockPair) blocks[j]).DataBytes;
  384. if (i < dataBytes.size())
  385. {
  386. result.appendBits(dataBytes.at(i), 8);
  387. }
  388. }
  389. }
  390. // Then, place error correction blocks.
  391. for (int i = 0; i < maxNumEcBytes; ++i)
  392. {
  393. for (int j = 0; j < blocks.Count; ++j)
  394. {
  395. ByteArray ecBytes = ((BlockPair) blocks[j]).ErrorCorrectionBytes;
  396. if (i < ecBytes.size())
  397. {
  398. result.appendBits(ecBytes.at(i), 8);
  399. }
  400. }
  401. }
  402. if (numTotalBytes != result.sizeInBytes())
  403. {
  404. // Should be same.
  405. throw new WriterException("Interleaving error: " + numTotalBytes + " and " + result.sizeInBytes() + " differ.");
  406. }
  407. }
  408. internal static ByteArray generateECBytes(ByteArray dataBytes, int numEcBytesInBlock)
  409. {
  410. int numDataBytes = dataBytes.size();
  411. int[] toEncode = new int[numDataBytes + numEcBytesInBlock];
  412. for (int i = 0; i < numDataBytes; i++)
  413. {
  414. toEncode[i] = dataBytes.at(i);
  415. }
  416. new ReedSolomonEncoder(GF256.QR_CODE_FIELD).encode(toEncode, numEcBytesInBlock);
  417. ByteArray ecBytes = new ByteArray(numEcBytesInBlock);
  418. for (int i = 0; i < numEcBytesInBlock; i++)
  419. {
  420. ecBytes.set_Renamed(i, toEncode[numDataBytes + i]);
  421. }
  422. return ecBytes;
  423. }
  424. /*/// <summary> Append mode info. On success, store the result in "bits".</summary>*/
  425. internal static void appendModeInfo(Mode mode, BitVector bits)
  426. {
  427. bits.appendBits(mode.Bits, 4);
  428. }
  429. /*/// <summary> Append length info. On success, store the result in "bits".</summary>*/
  430. internal static void appendLengthInfo(int numLetters, int version, Mode mode, BitVector bits)
  431. {
  432. int numBits = mode.getCharacterCountBits(Version.getVersionForNumber(version));
  433. if (numLetters > ((1 << numBits) - 1))
  434. {
  435. throw new WriterException(numLetters + "is bigger than" + ((1 << numBits) - 1));
  436. }
  437. bits.appendBits(numLetters, numBits);
  438. }
  439. /*/// <summary> Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits".</summary>*/
  440. internal static void appendBytes(System.String content, Mode mode, BitVector bits, System.String encoding)
  441. {
  442. if (mode.Equals(Mode.NUMERIC))
  443. {
  444. appendNumericBytes(content, bits);
  445. }
  446. else if (mode.Equals(Mode.ALPHANUMERIC))
  447. {
  448. appendAlphanumericBytes(content, bits);
  449. }
  450. else if (mode.Equals(Mode.BYTE))
  451. {
  452. append8BitBytes(content, bits, encoding);
  453. }
  454. else if (mode.Equals(Mode.KANJI))
  455. {
  456. appendKanjiBytes(content, bits);
  457. }
  458. else
  459. {
  460. throw new WriterException("Invalid mode: " + mode);
  461. }
  462. }
  463. internal static void appendNumericBytes(System.String content, BitVector bits)
  464. {
  465. int length = content.Length;
  466. int i = 0;
  467. while (i < length)
  468. {
  469. int num1 = content[i] - '0';
  470. if (i + 2 < length)
  471. {
  472. // Encode three numeric letters in ten bits.
  473. int num2 = content[i + 1] - '0';
  474. int num3 = content[i + 2] - '0';
  475. bits.appendBits(num1 * 100 + num2 * 10 + num3, 10);
  476. i += 3;
  477. }
  478. else if (i + 1 < length)
  479. {
  480. // Encode two numeric letters in seven bits.
  481. int num2 = content[i + 1] - '0';
  482. bits.appendBits(num1 * 10 + num2, 7);
  483. i += 2;
  484. }
  485. else
  486. {
  487. // Encode one numeric letter in four bits.
  488. bits.appendBits(num1, 4);
  489. i++;
  490. }
  491. }
  492. }
  493. internal static void appendAlphanumericBytes(System.String content, BitVector bits)
  494. {
  495. int length = content.Length;
  496. int i = 0;
  497. while (i < length)
  498. {
  499. int code1 = getAlphanumericCode(content[i]);
  500. if (code1 == - 1)
  501. {
  502. throw new WriterException();
  503. }
  504. if (i + 1 < length)
  505. {
  506. int code2 = getAlphanumericCode(content[i + 1]);
  507. if (code2 == - 1)
  508. {
  509. throw new WriterException();
  510. }
  511. // Encode two alphanumeric letters in 11 bits.
  512. bits.appendBits(code1 * 45 + code2, 11);
  513. i += 2;
  514. }
  515. else
  516. {
  517. // Encode one alphanumeric letter in six bits.
  518. bits.appendBits(code1, 6);
  519. i++;
  520. }
  521. }
  522. }
  523. internal static void append8BitBytes(System.String content, BitVector bits, System.String encoding)
  524. {
  525. sbyte[] bytes;
  526. try
  527. {
  528. //UPGRADE_TODO: Method 'java.lang.String.getBytes' was converted to 'System.Text.Encoding.GetEncoding(string).GetBytes(string)' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javalangStringgetBytes_javalangString'"
  529. bytes = SupportClass.ToSByteArray(System.Text.Encoding.GetEncoding(encoding).GetBytes(content));
  530. }
  531. catch (System.IO.IOException uee)
  532. {
  533. //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
  534. throw new WriterException(uee.ToString());
  535. }
  536. for (int i = 0; i < bytes.Length; ++i)
  537. {
  538. bits.appendBits(bytes[i], 8);
  539. }
  540. }
  541. internal static void appendKanjiBytes(System.String content, BitVector bits)
  542. {
  543. sbyte[] bytes;
  544. try
  545. {
  546. //UPGRADE_TODO: Method 'java.lang.String.getBytes' was converted to 'System.Text.Encoding.GetEncoding(string).GetBytes(string)' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javalangStringgetBytes_javalangString'"
  547. bytes = SupportClass.ToSByteArray(System.Text.Encoding.GetEncoding("Shift_JIS").GetBytes(content));
  548. }
  549. catch (System.IO.IOException uee)
  550. {
  551. //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
  552. throw new WriterException(uee.ToString());
  553. }
  554. int length = bytes.Length;
  555. for (int i = 0; i < length; i += 2)
  556. {
  557. int byte1 = bytes[i] & 0xFF;
  558. int byte2 = bytes[i + 1] & 0xFF;
  559. int code = (byte1 << 8) | byte2;
  560. int subtracted = - 1;
  561. if (code >= 0x8140 && code <= 0x9ffc)
  562. {
  563. subtracted = code - 0x8140;
  564. }
  565. else if (code >= 0xe040 && code <= 0xebbf)
  566. {
  567. subtracted = code - 0xc140;
  568. }
  569. if (subtracted == - 1)
  570. {
  571. throw new WriterException("Invalid byte sequence");
  572. }
  573. int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff);
  574. bits.appendBits(encoded, 13);
  575. }
  576. }
  577. }
  578. }