Trims the leading zeros from byte array. - Java java.lang

Java examples for java.lang:byte Array

Description

Trims the leading zeros from byte array.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] byeArray = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(java.util.Arrays.toString(trimZeroes(byeArray)));
    }/* ww w. j  a  v  a 2 s  .  c o m*/

    /**
     * Trims the leading zeros.
     * 
     * @param byeArray the byte array with possible leading zeros.
     * @return the byte array with no leading zeros.
     */
    public static byte[] trimZeroes(byte[] byeArray) {
        // count how many leading zeros
        int count = 0;
        while ((count < byeArray.length - 1) && (byeArray[count] == 0)) {
            count++;
        }
        if (count == 0) {
            // no leading zeros initially
            return byeArray;
        }
        byte[] trimmedByteArray = new byte[byeArray.length - count];
        System.arraycopy(byeArray, count, trimmedByteArray, 0,
                trimmedByteArray.length);
        return trimmedByteArray;
    }
}

Related Tutorials