Reputation: 21
i have 2 very large binary numbers (144 digits). I want to write them in different RandomAccessFiles and then read the files to memory and check to see which number is bigger. What i did so far:
1. I created a BigInteger:
BigInteger big = new BigInteger("01110101010010101010111100010101010101010101010110101010101010101010010101010101010101010101010101111010010101010",2);
2. I get the longValue:
big.longValue();
3.. I write the long to a randomaccessfile,read the files,compare the longs etc...
But if the binary is longer than the 'Long.maxvalue' what i did is wrong, correct?
So does anyone have any suggestions?
Can i handle large binary numbers otherwise?
Upvotes: 2
Views: 1810
Reputation: 17262
Obviously, your number is too large for a long.
I recommend you to export your BigInteger as a byte array using BigInteger.getByteArray()
, and then you can save it to a file (that's what we do in cryptography).
Also, the byte array can be converted back to a BigInteger using its contructor.
Upvotes: 0
Reputation: 157
eliminate initial zeros
Convert these numbers to Strings
else
take one by one digit from the beginning and compare.
if(string1 digit x = 0 & string 2 digit x=0) go to next digit
if(string1 digit x = 1 & string 2 digit x=0) String 1 is big
if(string1 digit x = 0 & string 2 digit x=1) String 2 is big
Upvotes: 0
Reputation: 5531
try comparing as below
BigInteger big1 = new BigInteger("01110101010010101010111100010101010101010101010110101010101010101010010101010101010101010101010101111010010101010",2);
BigInteger big2 = new BigInteger("01110101010010101010111100010101010101010101010110101010101010101010010101010101010101010101010101111010010101010",2);
int result =big1.compareTo(big2);
System.out.println(result);
Upvotes: 1