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?
int n=0;
for(byte b : token)
n = 10*n + (b-'0');
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With