From cc939b2ebe04a5552d9a3ac43e250a7db8d49436 Mon Sep 17 00:00:00 2001 From: Project Nayuki Date: Wed, 22 Aug 2018 17:57:40 +0000 Subject: [PATCH] Tweaked Java code to prevent arithmetic overflow for huge input data. --- java/io/nayuki/qrcodegen/BitBuffer.java | 2 +- java/io/nayuki/qrcodegen/QrSegment.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/java/io/nayuki/qrcodegen/BitBuffer.java b/java/io/nayuki/qrcodegen/BitBuffer.java index d1ab920..8da04ee 100644 --- a/java/io/nayuki/qrcodegen/BitBuffer.java +++ b/java/io/nayuki/qrcodegen/BitBuffer.java @@ -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; diff --git a/java/io/nayuki/qrcodegen/QrSegment.java b/java/io/nayuki/qrcodegen/QrSegment.java index a4e8a2a..91098a2 100644 --- a/java/io/nayuki/qrcodegen/QrSegment.java +++ b/java/io/nayuki/qrcodegen/QrSegment.java @@ -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);