Java Array Subtract subtract(byte[] a, byte[] b)

Here you can find the source of subtract(byte[] a, byte[] b)

Description

a - b

License

Open Source License

Parameter

Parameter Description
a a parameter
b a parameter

Declaration

public static byte[] subtract(byte[] a, byte[] b) 

Method Source Code

//package com.java2s;
/**/*from w  w w .  j av  a 2  s.  c o m*/
 * ?????????? unsigned ????????????????????????????????????????
 *
 * License : MIT License
 */

public class Main {
    /**
     * a - b
     * @param a
     * @param b
     * @return
     */
    public static byte[] subtract(byte[] a, byte[] b) {
        if (a == null)
            throw new IllegalArgumentException("b1 should not be null");
        if (b == null)
            throw new IllegalArgumentException("b2 should not be null");
        if (a.length != b.length)
            throw new IllegalArgumentException(
                    "byte array length should be same");

        int len = a.length;
        byte[] result = new byte[len];
        int borrow = 0;
        for (int i = len - 1; 0 <= i; i--) {
            int i1 = byte2int(a[i]); // 0 <= i1 <= 255(0xff)
            int i2 = byte2int(b[i]); // 0 <= i2 <= 255(0xff)
            int col = i1 - i2 + borrow;
            borrow = (col >> 8);
            result[i] = int2byte(col);
        }
        return result;
    }

    public static int byte2int(byte b) {
        return ((int) b & 0x000000ff);
    }

    public static byte int2byte(int i) {
        return (byte) (i & 0x000000ff);
    }
}

Related

  1. arraySubtract(double[] x1, double[] x2)
  2. arraySubtract(final Double[] first, final Double[] second)
  3. subtract(double[] a, double[] b)
  4. subtract(double[] a, double[] b)
  5. subtract(double[] a, double[] b)
  6. subtract(double[] a, double[] b)