Reputation: 341
I have two byte arrays that I am trying to add using
BigInteger n1=new BigInteger(byte[] a1);
BigInteger n2=new BigInteger(byte[] a2);
BigInteger sum=a1.add(a2);
byte[] as=sum.toByteArray();
This is what I got:
a1=4A4A3E502602CE0C3D1792D5A2C6BADFE701E5C668FBE1D92F19923CD2A5143B
a2=FFE735AE9FB702A6C08D3ED57CB6CCF7CBB74F6F8D3F820A837A9775AF953F0D
as=4A3173FEC5B9D0B2FDA4D1AB1F7D87D7B2B93535F63B63E3B29429B2823A5348
Looking at the most significant byte, the addition of 0x4A and 0xFF generate a carry that is lost. I would expect that adding two 32byte integers would result in a 33byte integer (this case since there is a carry).
Upvotes: 0
Views: 76
Reputation: 341
BigInteger is signed.
Considering only the most significant byte:
0x4A + 0xFF = 74 + -1 = 73 = 0x49 + 1 (carry from previous byte) = 0x4A
To solve this issue fast, I've added a most significant zero in both arrays.
004A4A3E502602CE0C3D1792D5A2C6BADFE701E5C668FBE1D92F19923CD2A5143B
00FFE735AE9FB702A6C08D3ED57CB6CCF7CBB74F6F8D3F820A837A9775AF953F0D
014A3173FEC5B9D0B2FDA4D1AB1F7D87D7B2B93535F63B63E3B29429B2823A5348
Upvotes: 1
Reputation: 5455
Are you sure about the content of your byte arrays a1
and a2
?
BigInteger b1 = new BigInteger("4A4A3E502602CE0C3D1792D5A2C6BADFE701E5C668FBE1D92F19923CD2A5143B", 16);
BigInteger b2 = new BigInteger("FFE735AE9FB702A6C08D3ED57CB6CCF7CBB74F6F8D3F820A837A9775AF953F0D", 16);
BigInteger c = b1.add(b2);
System.out.println(c.toString(16));
Produces:
4a4a3e502602ce0c3d1792d5a2c6badfe701e5c668fbe1d92f19923cd2a5143b
ffe735ae9fb702a6c08d3ed57cb6ccf7cbb74f6f8d3f820a837a9775af953f0d
14a3173fec5b9d0b2fda4d1ab1f7d87d7b2b93535f63b63e3b29429b2823a5348
With the expected carry.
Upvotes: 5