Skip to content

Commit 242572f

Browse files
authored
Merge pull request #32 from RUB-NDS/ArrayConverter-ReverseByteOrder
added method in ArrayConverter to reverse bytes in an array
2 parents 9fbf66e + e5eb936 commit 242572f

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

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

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ public static String bytesToHexString(byte[] array, boolean usePrettyPrinting, b
177177

178178
/**
179179
* Like bytesToHexString() without any formatting.
180-
*
180+
*
181181
* @param array
182182
* byte array
183183
* @return hex string
@@ -401,4 +401,22 @@ public static byte[] longToUint48Bytes(long input) {
401401

402402
return output;
403403
}
404+
405+
/**
406+
* Reverses the order of a byte array: So, [0x00,0x01,0x02,0x03] will be
407+
* returned as [0x03,0x02,0x01,0x00]
408+
*
409+
* @param array
410+
* the byte array to reverse
411+
* @return byte array with reversed byte order
412+
*/
413+
public static byte[] reverseByteOrder(byte[] array) {
414+
int length = array.length;
415+
byte[] temp = new byte[length];
416+
int counter = length - 1;
417+
for (int i = 0; i < length; i++) {
418+
temp[i] = array[counter--];
419+
}
420+
return temp;
421+
}
404422
}

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,4 +237,14 @@ public void testBytesToHexString_ModifiableByteArray() {
237237
ArrayConverter.bytesToHexString(toTest));
238238
}
239239

240+
/**
241+
* Test of reverseByteOrder method, of class ArrayConverter.
242+
*/
243+
@Test
244+
public void testReverseByteOrder() {
245+
byte[] array = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04 };
246+
247+
assertArrayEquals("Testing byte order reversion", new byte[] { 0x04, 0x03, 0x02, 0x01, 0x00 },
248+
ArrayConverter.reverseByteOrder(array));
249+
}
240250
}

0 commit comments

Comments
 (0)