bkrause404
bkrause404

Reputation: 19

Byte Array Subtraction

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!

Upvotes: 0

Views: 1182

Answers (1)

user2357112
user2357112

Reputation: 281624

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))

Upvotes: 1

Related Questions