开发者

Problem with a number when storing in BigInteger and retrieving back

开发者 https://www.devze.com 2023-03-26 15:09 出处:网络
BigInteger bx=new BigInteger(\"5888561920\"); System.out.println(\"bx:\"+bx); byte x[]=new byte[5]; x=bx.toByteArray();
BigInteger bx=new BigInteger("5888561920");

System.out.println("bx:"+bx);

byte x[]=new byte[5];

x=bx.toByteArray();

for(k=4;cnt<4;k--)
{

    cnt++;

    t[k-1]=x[k];
}

for(i=0;i<4;i++)

        System.out.print(" "+t[i]);

System.out.println("\nbig: "+toInt(t));

The output for the above code is:

bx:5888561920

 94 -4 83 0

big: 1593594624

The problem here is when i am converting a big integer into a byte array and again converting the same byte array to a big integer, the values of big integer are changing. But when i replace the number "5888561920" with "2944280960" or "3806908688" there is no problem i am getting开发者_如何学JAVA the same number as output. What is the problem here? Is the problem with BigInteger or "5888561920"

I have written the toInt method myself:

public static BigInteger toInt(byte[] b){

     String st=new String();
    for(int k=3;k>=0;k--){
        for(int i=0;i<8;i++)
        {
            if ((b[k] & 0x01) == 1)
            {
                st="1"+st;
            }
            else
            {
                st="0"+st;
            }
            b[k]=  (byte) (b[k] >> 1);
        }
    }

    BigInteger bi=new BigInteger(st,2);

    return bi;
}


In toInt(), you're concatenating the 32 least significant bits (k=0..3 x i=0..7) of the number.

5888561920 is larger than a 32-bit number. In fact its binary representation (according to Windows Calc) is 101011110111111000101001100000000, which is 33 bits long. You've truncated the most significant bit.

2944280960 and 3806908688 fit within 32 bits (bits 33 and beyond would all be zeroes anyway).

So I guess you do need that fifth byte, after all : )


The lower 4 bytes of 5888561920 is (5888561920 % 2^32) == 1593594624

If you want to store this number you need more than 4 bytes.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号