0

I'm trying to implement my own version of BigInteger exclusively using byte arrays (byte[]) to represent the integers. As of right now, I have my addition method working:

  public static byte[] add(byte[] data1, byte[] data2) {
    if(data1.length!=65 || data2.length!=65)
      throw new IllegalArgumentException();
    byte[] result=new byte[65];
    for(int i=64, overflow=0; i>=0; i--) {
      int v = (data1[i]&0xff)+(data2[i]&0xff)+overflow;
      result[i]=(byte)v;
      overflow=v>>>8;
    }
    return result;
  }

However, I'm having trouble implementing my subtraction method. Is there any way for me to relatively easily extrapolate a subtraction from my addition method or is it another process entirely. Thanks!

bkrause404
  • 19
  • 8
  • Subtraction is like addition, but you use a borrow. But be sure to always extract the smaller value from the larger. Afterwards, just adjust the sign. Such things work best if you use sign-magnitude (like most BigInteger implementations do), and are a little harder if you use two's complement. Sign-magnitude means that the value in your byte array is always positive (and unsigned) and that there is an extra bit representing the sign. It is not hard to work out the logic for when the sign should be flipped and when not. – Rudy Velthuis Apr 13 '17 at 12:26

1 Answers1

1

Is there any way for me to relatively easily extrapolate a subtraction from my addition method or is it another process entirely.

Implement negation, and subtraction can just be

add(arg1, negate(arg2))
user2357112
  • 260,549
  • 28
  • 431
  • 505
  • For the negation, I'm confused on how, as i'm traversing byte by byte, I would accomplish the negation. – bkrause404 Apr 12 '17 at 18:23
  • So if this is my byte array: [0, -125, 67, 40, -18, -19, 96, 18, -9, 77, 25, 119, -24, -58, 89, -7, -114, 25, 3, 43, -29, 87, -61, -48, 65, 77, 126, 4, -49, 27, -48, -86, -86, -19, -91, 72, -63, -91, -15, -16, 68, 107, -17, 104, 64, 36, -19, 53, 49, 113, -88, -5, -3, -95, 105, 9, 98, 113, 126, 61, -47, 24, -91, -121, -73], i'm confused would I negate each byte in the array or some other method? – bkrause404 Apr 12 '17 at 18:24
  • You should treat the byte array as unsigned. Otherwise things get very messy. So your -125 should be regarded as +0x83 (+131), etc.Negating is a possibility, but takes twice as long, because you first traverse the array to negate, and then traverse it *again* to add, which, in the end, can get pretty slow. Directly subtracting (see my other comment too) is much easier. Just try with small numbers and then expand that to BigIntegers, to see what you should do. – Rudy Velthuis Apr 13 '17 at 12:29