/** * Treat the byte[] as an unsigned series of bytes, most significant bits first. Start by adding * 1 to the rightmost bit/byte and carry over all overflows to the more significant bits/bytes. * * @param input The byte[] to increment. * @return The incremented copy of "in". May be same length or 1 byte longer. */ public static byte[] unsignedCopyAndIncrement(final byte[] input) { byte[] copy = copy(input); if (copy == null) { throw new IllegalArgumentException("cannot increment null array"); } for (int i = copy.length - 1; i >= 0; --i) { if (copy[i] == -1) {// -1 is all 1-bits, which is the unsigned maximum copy[i] = 0; } else { ++copy[i]; return copy; } } // we maxed out the array byte[] out = new byte[copy.length + 1]; out[0] = 1; System.arraycopy(copy, 0, out, 1, copy.length); return out; }
/** * Treat the byte[] as an unsigned series of bytes, most significant bits first. Start by adding * 1 to the rightmost bit/byte and carry over all overflows to the more significant bits/bytes. * * @param input The byte[] to increment. * @return The incremented copy of "in". May be same length or 1 byte longer. */ public static byte[] unsignedCopyAndIncrement(final byte[] input) { byte[] copy = copy(input); if (copy == null) { throw new IllegalArgumentException("cannot increment null array"); } for (int i = copy.length - 1; i >= 0; --i) { if (copy[i] == -1) {// -1 is all 1-bits, which is the unsigned maximum copy[i] = 0; } else { ++copy[i]; return copy; } } // we maxed out the array byte[] out = new byte[copy.length + 1]; out[0] = 1; System.arraycopy(copy, 0, out, 1, copy.length); return out; }