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

pull/39/merge
Project Nayuki 6 years ago
parent 4ca232b949
commit cc939b2ebe

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

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

Loading…
Cancel
Save