Reverse byte array - Java java.lang

Java examples for java.lang:byte Array

Description

Reverse byte array

Demo Code


//package com.java2s;

import javax.annotation.Nullable;

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

    /**
     * Reverse byte array
     */
    @Nullable
    public static byte[] reverse(@Nullable byte[] data) {
        if (data == null)
            return null;

        int length = data.length;
        byte[] result = new byte[length];
        if (length == 0)
            return result;

        for (int i = 0; i < length; i++) {
            result[i] = data[length - i - 1];
        }

        return result;
    }
}

Related Tutorials