Java tutorial
//package com.java2s; //License from project: Apache License public class Main { public static byte[] normalizeArray(byte[] bytes, int expectedLength) throws Exception { if (bytes.length > expectedLength) { boolean invalid = false; for (int i = bytes.length - 1 - expectedLength; i >= 0; i--) { if (bytes[i] != 0) { invalid = true; break; } } if (invalid) throw new Exception("Longer byte array than expected by caller."); } if (bytes.length == expectedLength) return bytes; return preAppendHighZeroPadding(bytes, expectedLength - bytes.length); } public static byte[] preAppendHighZeroPadding(byte[] bytes, int zeroes) { byte[] result = new byte[bytes.length + zeroes]; for (int i = 0; i < result.length; i++) { if (i >= zeroes) { result[i] = bytes[i - zeroes]; } else { result[i] = 0; } } return result; } }