Reverse the order of a given byte array - Java java.lang

Java examples for java.lang:byte Array

Description

Reverse the order of a given byte array

Demo Code

/*//from ww w .j  a v  a 2  s.  c  o  m
 * @(#) ByteArrayUtils.java
 *
 * This code is part of the JAviator project: javiator.cs.uni-salzburg.at
 * Copyright (c) 2009  Clemens Krainer
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
//package com.java2s;

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

    /**
     * Reverse the order of a given byte array
     *  
     * @param a the byte array to be reversed.
     * @return the byte array in reversed order.
     */
    public static byte[] reverse(byte[] a) {
        byte[] b = new byte[a.length];
        for (int k = 0; k < a.length; k++)
            b[k] = a[a.length - 1 - k];
        return b;
    }
}

Related Tutorials