简体   繁体   English

为什么对于很长的二进制字符串返回负值?

[英]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 . 它返回-28。
Why is the memory out of range? 为什么内存超出范围? or is my code is incorrect? 还是我的代码不正确?

You are probably overrunning the length of an int. 您可能超出了int的长度。 Integers in java are 32 bit and that binary string is 91 bits. Java中的整数是32位,而二进制字符串是91位。

Try using something like BigInteger instead, which will not overflow. 尝试改用BigInteger东西,它不会溢出。 In fact, BigInteger has a built-in method for this: 实际上, BigInteger为此提供了一个内置方法:

BigInteger result = new BigInteger(a, 2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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