user462982
user462982

Reputation: 1645

Efficient way to convert a hex representation of a number to a decimal value

I have a byte[5] array which represents a decimal number when printed as a hex string. Two digits can be stored in one byte, the hex characters are not used. E.g.

[0x11,0x45,0x34,0x31,0x21] -> 1145343121.

Is there a more efficient way in Java (some bitshifting magic maybe) to do the conversion to a decimal number other than

long result = Long.parseLong(byteToHexString(bytes[]));?

An efficient conversion vice versa would also be interesting...

Upvotes: 2

Views: 1298

Answers (3)

user207421
user207421

Reputation: 310884

After Knuth, Art of Computer Programming, Vol II Seminumerical Algorithms, answer to exercise 4.4(19):

public long binaryValue(long bcd)
{
    long    x = bcd;
    x -= ((x & 0xf0f0f0f0f0f0f0f0L) >> 4)*(0x10-10);
    x -= ((x & 0xff00ff00ff00ff00L) >> 8)*(0x100-100);
    x -= ((x & 0xffff0000ffff0000L) >> 16)*(0x10000-10000);
    x -= ((x & 0xffffffff00000000L) >> 32)*(0x100000000L-100000000);
    return x;
}

Upvotes: 1

Prashant Bhate
Prashant Bhate

Reputation: 11087

Here you go, trick is to nibble a nibble at a time !

    byte[] buf = { 0x11, 0x45, 0x34, 0x31, 0x21 };
    long result = 0;
    for (int i = 0; i < buf.length; i++) {
        result = result * 100 + (buf[i] >> 4 & 0XF) * 10 + (buf[i] & 0XF);
    }
    System.out.println(result);

Output

1145343121

Upvotes: 2

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

((a[0]>>>4)*1000000000L + (a[0]&15)*100000000L +
 (a[1]>>>4)*  10000000L + (a[1]&15)*  1000000L +
 (a[2]>>>4)*    100000L + (a[2]&15)*    10000L +
 (a[3]>>>4)*      1000L + (a[3]&15)*      100L +
 (a[4]>>>4)*        10L + (a[4]&15))

Upvotes: 3

Related Questions