Java examples for java.lang:byte Array
Returns a byte array left padded of pad Size zero bytes
/*/*from w w w. j a v a 2s .c om*/ Copyright 2013 Stefano Fratini (mail@stefanofratini.it) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //package com.java2s; import java.io.ByteArrayOutputStream; import java.io.IOException; public class Main { public static void main(String[] argv) throws Exception { byte[] src = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 }; int padSize = 2; System.out .println(java.util.Arrays.toString(padLeft(src, padSize))); } /** * Returns a byte array left padded of padSize zero bytes * @param src * @param padSize * @return */ public static byte[] padLeft(byte[] src, int padSize) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { while (padSize > 0) { padSize--; bout.write(0); } bout.write(src); } catch (IOException ex) { throw new RuntimeException(ex); } return bout.toByteArray(); } }