A quick way to convert a byte [] string to an Integer value

I am reading a large file from disk. This file contains only digits encoded as plain old ASCII. At the moment, I am reading the pieces, 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 convert to String and then parse the string into 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 can be done faster. For example, raw bytes for numbers 1,2,3 are 49.50.51. Any ideas for hacks?

+6
source share
3 answers
  int n=0; for(byte b : token) n = 10*n + (b-'0'); 
+7
source

You cannot perform binary arithmetic exactly with base numbers 10, but you can perform decimal arithmetic. Assuming higher order numbers 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; } 
+2
source

to try

  byte[] a = { 1, 2, 3 }; for (int i = 0; i < a.length; i++) { a[i] += '0'; } int n = Integer.parseInt(new String(a)); System.out.println(n); 

Output

 123 
0
source

All Articles