D. van der Bleek
D. van der Bleek

Reputation: 23

Taking a string representation of a large integer and converting it to a byte array in Java

Basically, my problem is two-fold, and refers pretty specifically to the Bitcoin RPC. I am writing a miner in Java for Litecoin (a spinoff of BTC) and need to take a string that looks like:

000000000000000000000000000000000000000000000000000000ffff0f0000

Convert it to look like

00000fffff000000000000000000000000000000000000000000000000000000

(Which I believe is switching from little endian to big endian)

I then need to turn that string into a byte array --

I've looked at the Hex class from org.apache, String.toByte(), and a piece of code that looks like:

public static byte[] toByta(char[] data) {
    if (data == null) return null;
    // ----------
    byte[] byts = new byte[data.length * 2];
    for (int i = 0; i < data.length; i++)
        System.arraycopy(toByta(data[i]), 0, byts, i * 2, 2);
    return byts;
}

So essentially: What is the best way, in Java to change endianness? And what is the best way to take a string representation of a number and convert it to a byte array to be hashed?

EDIT: I had the wrong result after changing the endian.

Upvotes: 2

Views: 522

Answers (1)

user949300
user949300

Reputation: 15729

  1. Integer and BigInteger both have toString methods taking a radix, so you can get the hex String.
  2. You can make a StringBuffer from that String and call reverse().
  3. You then convert back to a String using toString(), then get the bytes via getBytes();

Don't know if this is "best" but it requires little work on your part.

If you need better speed, call getBytes() on the original wrong direction hex string (from step 1) and reverse it in place using a for loop. e.g.

for (int i=0; i<bytes.length/2; i++) {
   byte temp = bytes[i];
   bytes[i] = bytes[bytes.length - i];
   bytes[bytes.length - i] = temp;
}

Upvotes: 2

Related Questions