-1

Is there a simple way how to make byte arrays adding?

I mean a mathematical adding (no concatenation):

00 00 FF    
00 00 FF
--------
00 01 FE

I can achieve that by converting the byte array to a numeric format, but this approach is limited by max value of the number format. I need a solution that can work with much larger values than standard formats provide.

Jolinar
  • 866
  • 8
  • 16
  • 2
    Show us your attempt – Luigi Cortese Sep 16 '15 at 15:35
  • 3
    Have you tried BigInteger? – nneonneo Sep 16 '15 at 15:36
  • 2
    possible duplicate of [How to add two numbers of any length in java?](http://stackoverflow.com/questions/3748846/how-to-add-two-numbers-of-any-length-in-java) – dimo414 Sep 16 '15 at 15:37
  • 2
    You know how long addition works, you've learned this in elementary school. It's a different base and there's a funny thing when you have to carry past the end of the array, but you can do it I'm sure. – harold Sep 16 '15 at 15:37

1 Answers1

3

You can use BigInteger which has no theoretical limit to it's size. In practice, obviously, if the number of bytes is too big to fit in memory than you need to take a different approach.

public void test() {
    BigInteger a = new BigInteger(new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0xff});
    BigInteger b = new BigInteger(new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0xff});

    System.out.println(a.toString(16) + "+" + b.toString(16) + "=" + a.add(b).toString(16));
}

prints ff+ff=1fe.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213