Java Array Trim trim(byte[] data)

Here you can find the source of trim(byte[] data)

Description

Trim the byte array by removing the leading 0's.

License

Apache License

Parameter

Parameter Description
data The data to trim.

Return

The trimmed data.

Declaration

public static byte[] trim(byte[] data) 

Method Source Code

//package com.java2s;
/*//w w  w .  ja v  a  2  s .c  o  m
 * Licensed to the Warcraft4J Project under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The Warcraft4J Project licenses
 * this file to you 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.
 */

import java.util.Arrays;

public class Main {
    /**
     * Trim the byte array by removing the leading 0's.
     * <p>
     * This function is mostly useful in combination with functions like {@code BigInteger#toByteArray()} which prepends with a signing byte (0x00 in case of postive numbers).
     *
     * @param data The data to trim.
     *
     * @return The trimmed data.
     */
    public static byte[] trim(byte[] data) {
        int idx = 0;
        while (idx < data.length) {
            if (data[idx] != 0) {
                break;
            }
            idx++;
        }
        byte[] trimmedData;
        if (idx > 0 && idx < data.length) {
            trimmedData = Arrays.copyOfRange(data, idx, data.length);
        } else {
            trimmedData = data;
        }
        return trimmedData;
    }
}

Related

  1. rtrim(long[] array)
  2. safeTrim(byte[] ba, int len)
  3. safeTrim(final char[] ca, final int len)
  4. trim(byte[] bytes)
  5. trim(byte[] bytes, int endMargin)
  6. trim(byte[] src, byte padding, boolean right, int minLength)
  7. trim(String s, char delimit[])
  8. trim(String[] args)
  9. trim(String[] array)