Skip to content

Commit 02cc135

Browse files
authored
Merge pull request #37 from RUB-NDS/numberConverterFixes
intToBytes and longToBytes had errors when working with arrays larger…
2 parents 6bfc01f + cfe2e0e commit 02cc135

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

src/main/java/de/rub/nds/modifiablevariable/util/ArrayConverter.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,8 @@ public static byte[] intToBytes(int value, int size) {
7272
}
7373
byte[] result = new byte[size];
7474
int shift = 0;
75-
for (int i = size - 1; i >= 0; i--) {
75+
int finalPosition = ((size > Integer.BYTES) ? (size - Integer.BYTES) : 0);
76+
for (int i = size - 1; i >= finalPosition; i--) {
7677
result[i] = (byte) (value >>> shift);
7778
shift += 8;
7879
}
@@ -96,7 +97,8 @@ public static byte[] longToBytes(long value, int size) {
9697
}
9798
byte[] result = new byte[size];
9899
int shift = 0;
99-
for (int i = size - 1; i >= 0; i--) {
100+
int finalPosition = ((size > Long.BYTES) ? (size - Long.BYTES) : 0);
101+
for (int i = size - 1; i >= finalPosition; i--) {
100102
result[i] = (byte) (value >>> shift);
101103
shift += 8;
102104
}

src/test/java/de/rub/nds/modifiablevariable/util/ArrayConverterTest.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,34 @@ public void testIntToBytes() {
4444
assertArrayEquals("The conversion result of 5717 should be {0x16} {0x55}", new byte[] { 0x16, 0x55 }, result);
4545
}
4646

47+
@Test
48+
public void testIntToBytesOverflow() {
49+
int toParse = 5717;
50+
byte[] result = ArrayConverter.intToBytes(toParse, 5);
51+
assertArrayEquals("The conversion result of 5717 should be {0x00} {0x00} {0x00} {0x16} {0x55}", new byte[] {
52+
0x00, 0x00, 0x00, 0x16, 0x55 }, result);
53+
}
54+
55+
/**
56+
* Test of intToBytes method, of class ArrayConverter.
57+
*/
58+
@Test
59+
public void testLongToBytes() {
60+
long toParse = 5717;
61+
byte[] result = ArrayConverter.longToBytes(toParse, 2);
62+
assertArrayEquals("The conversion result of 5717 should be {0x16} {0x55}", new byte[] { 0x16, 0x55 }, result);
63+
}
64+
65+
@Test
66+
public void testLongToBytesOverflow() {
67+
int toParse = 5717;
68+
byte[] result = ArrayConverter.longToBytes(toParse, 10);
69+
assertArrayEquals(
70+
"The conversion result of 5717 should be {0x00} {0x00} {0x00} {0x00} {0x00} {0x00} {0x00} {0x00} "
71+
+ "{0x16} {0x55}", new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x55 },
72+
result);
73+
}
74+
4775
/**
4876
* Test of bytesToInt method, of class ArrayConverter.
4977
*/

0 commit comments

Comments
 (0)