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:

The values we see are the ASCII or Unicode values for the eqivalent characters.
There are several ways to extract their equivalent character as int
s:
- 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.
- @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).