简体   繁体   中英

Why is it returning a negative value for a very long binary string?

public long bin_to_dec() {
    int leng = a.length();

    for (int i = 0, j = (leng - 1); i < leng; i++, j--) {

        int number = Character.getNumericValue(a.charAt(j));
        result = result + (number * ((long) Math.pow(2, i)));

    }
    return result;
}  

This code takes a binary string as argument and return it's decimal value .
but for a long string ie

(111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111) 

it returns -28 .
Why is the memory out of range? or is my code is incorrect?

You are probably overrunning the length of an int. Integers in java are 32 bit and that binary string is 91 bits.

Try using something like BigInteger instead, which will not overflow. In fact, BigInteger has a built-in method for this:

BigInteger result = new BigInteger(a, 2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM