Implement ReverseDwordBytes. Resolves issue 100

This commit is contained in:
Miron Cuperman (devrandom) 2011-10-31 17:28:01 +00:00
parent a88bb0bc1c
commit dff3b2b45a
2 changed files with 37 additions and 3 deletions

View File

@ -16,17 +16,16 @@
package com.google.bitcoin.core;
import org.bouncycastle.crypto.digests.RIPEMD160Digest;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Date;
import org.bouncycastle.crypto.digests.RIPEMD160Digest;
/**
* A collection of various utility methods that are helpful for working with the BitCoin protocol.
* To enable debug logging from the library, run with -Dbitcoinj.logging=true on your command line.
@ -189,6 +188,27 @@ public class Utils {
buf[i] = bytes[bytes.length - 1 - i];
return buf;
}
/**
* Returns a copy of the given byte array with the bytes of each double-word (4 bytes) reversed.
*
* @param bytes length must be divisible by 4.
* @param trimLength trim output to this length. If positive, must be divisible by 4.
*/
public static byte[] reverseDwordBytes(byte[] bytes, int trimLength) {
assert bytes.length % 4 == 0;
assert trimLength < 0 || trimLength % 4 == 0;
byte[] rev = new byte[trimLength >= 0 && bytes.length > trimLength ? trimLength : bytes.length];
for (int i = 0; i < rev.length; i += 4) {
System.arraycopy(bytes, i, rev, i , 4);
for (int j = 0; j < 4; j++) {
rev[i + j] = bytes[i + 3 - j];
}
}
return rev;
}
public static long readUint32(byte[] bytes, int offset) {
return ((bytes[offset++] & 0xFFL) << 0) |

View File

@ -21,6 +21,7 @@ import static junit.framework.Assert.fail;
import static com.google.bitcoin.core.Utils.*;
import org.junit.Assert;
import org.junit.Test;
public class UtilsTest {
@ -51,4 +52,17 @@ public class UtilsTest {
assertEquals("1.23", bitcoinValueToFriendlyString(toNanoCoins(1, 23)));
assertEquals("-1.23", bitcoinValueToFriendlyString(toNanoCoins(1, 23).negate()));
}
@Test
public void testReverseBytes() {
Assert.assertArrayEquals(new byte[] {1,2,3,4,5}, Utils.reverseBytes(new byte[] {5,4,3,2,1}));
}
@Test
public void testReverseDwordBytes() {
Assert.assertArrayEquals(new byte[] {1,2,3,4,5,6,7,8}, Utils.reverseDwordBytes(new byte[] {4,3,2,1,8,7,6,5}, -1));
Assert.assertArrayEquals(new byte[] {1,2,3,4}, Utils.reverseDwordBytes(new byte[] {4,3,2,1,8,7,6,5}, 4));
Assert.assertArrayEquals(new byte[0], Utils.reverseDwordBytes(new byte[] {4,3,2,1,8,7,6,5}, 0));
Assert.assertArrayEquals(new byte[0], Utils.reverseDwordBytes(new byte[0], 0));
}
}