Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast way to convert a byte[] string to its Integer value

I am reading a large file from disk. That file just contains numbers, encoded as plain old ASCII. At the moment, I am reading in chunks, and then doing something like this:

byte[] token;  // bytes representing a bunch of numbers
int n = Integer.parseInt(new String(token));

In other words, I am converting to a String and then parsing the String to Integer. I would like to know if there is a way to use fast operations like shifting and binary arithmetic instead?

I suspect that this could be made faster. For example, the raw bytes for the numbers 1,2,3 are 49,50,51. Any ideas for hacks?

like image 751
Dave Avatar asked Mar 06 '13 01:03

Dave


2 Answers

    int n=0;
    for(byte b : token)
        n = 10*n + (b-'0');
like image 159
irreputable Avatar answered Nov 15 '22 00:11

irreputable


You can't do binary arithmetic exactly with base 10 numbers, but you can do decimal arithmetic. Assuming that higher-order digits come first:

byte[] token;
long n = 0;
long pow = 1;
for( int i = token.length - 1; i >= 0; i-- ) {
  n += (token[i]-48) * pow;
  pow *= 10;
}
like image 26
Andrew Mao Avatar answered Nov 15 '22 01:11

Andrew Mao