Question

First, this sounds like the problem here: How to convert a byte array to its numeric value (Java)?

But the origin of my Byte-Array is a String, something like this:

byte[] foo = new byte[8];
foo = "12345678".getBytes();

Is there a faster way (yes its really about doing this quick) than
Integer.parseInt(new String(foo))? The String contains only digits which represent a Integer.

Was it helpful?

Solution

try this

    int res = 0;
    for(int i = foo.length -1, m = 1; i >=0; i--, m *= 10) {
        res += (foo[i] & 0xF) * m; 
    }

OTHER TIPS

You could try something like this:

byte foo[] = "12345678".getBytes();
//Since it is an 'integer' essentially, it will contain ASCII values of decimal digits.
long num = 0;  //Store number here.
for(int i = foo.length - 1; i >= 0; i--)
{
    num = num * 10 + (foo[i] - '0'); // or (foo[i] - 48) or (foo[i] & 0xf)
}

num stores the required number.

Precaution: Make sure you use decimal number only.


EDIT:

The Mechanism

On calling getBytes() of the String "12345678", the byte[] returned is as follows:

enter image description here

The values we see are the ASCII or Unicode values for the eqivalent characters. There are several ways to extract their equivalent character as ints:

  1. Since the arrangement of the digit chars, i.e. '0', '1', '2', etc. are done in the desired order - ascending and sequentially, we can extract the characters by subtrcting the ASCII value of '0' i.e. 48.
  2. @Evgeniy Dorofeev correctly pointed out the method of masking:

'0' => 48 => 11 0000

We notice that if we extract the last 4 bits, we get the required int. To do this, we need to extract them in the following way. Let us take foo[1], i.e. 50

  50      & 0xf  (original)
= 50      & 15   (in Decimal)
= 11 0010 & 1111 (in Binary)
= 0010           (result)
= 2              (Decimal)

Hence, the required digit is obtained. It in necessary to add it to num int the correct way (which I expect of every programmer to have some knowledge about).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top