Tweaked Java code to prevent arithmetic overflow for huge input data.

This commit is contained in:
Project Nayuki 2018-08-22 17:57:40 +00:00
parent 4ca232b949
commit cc939b2ebe
2 changed files with 3 additions and 3 deletions

View File

@ -82,7 +82,7 @@ public final class BitBuffer implements Cloneable {
* @return this sequence as a new array of bytes (not {@code null})
*/
public byte[] getBytes() {
byte[] result = new byte[(bitLength + 7) / 8];
byte[] result = new byte[(bitLength + 7) >>> 3]; // Round up to whole byte, won't overflow
for (int i = 0; i < bitLength; i++)
result[i >>> 3] |= data.get(i) ? 1 << (7 - (i & 7)) : 0;
return result;

View File

@ -71,7 +71,7 @@ public final class QrSegment {
BitBuffer bb = new BitBuffer();
int i;
for (i = 0; i + 3 <= digits.length(); i += 3) // Process groups of 3
for (i = 0; i <= digits.length() - 3; i += 3) // Process groups of 3
bb.appendBits(Integer.parseInt(digits.substring(i, i + 3)), 10);
int rem = digits.length() - i;
if (rem > 0) // 1 or 2 digits remaining
@ -96,7 +96,7 @@ public final class QrSegment {
BitBuffer bb = new BitBuffer();
int i;
for (i = 0; i + 2 <= text.length(); i += 2) { // Process groups of 2
for (i = 0; i <= text.length() - 2; i += 2) { // Process groups of 2
int temp = ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45;
temp += ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1));
bb.appendBits(temp, 11);