2

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...

user462982
  • 1,635
  • 1
  • 16
  • 26

3 Answers3

3
((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))
x4u
  • 13,877
  • 6
  • 48
  • 58
Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
2

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
Prashant Bhate
  • 10,907
  • 7
  • 47
  • 82
  • Yeah, thanks, works very well and looks short and sweet. Did a small test: Outperforms the trivial method by a factor of 6x. – user462982 Nov 20 '11 at 23:30
1

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;
}
user207421
  • 305,947
  • 44
  • 307
  • 483