Mega Code Archive

 
Categories / Java / File Input Output
 

Invert the endianness of words (4 bytes) in the given byte array starting at the given offset and repeating length4 time

/*  *  Licensed to the Apache Software Foundation (ASF) under one  *  or more contributor license agreements.  See the NOTICE file  *  distributed with this work for additional information  *  regarding copyright ownership.  The ASF 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.  *  */ /**  * ByteUtilities.java - Byte manipulation functions.  *   * @author <a href="http://mina.apache.org">Apache MINA Project</a>  * @since MINA 2.0.0-M3  */ public class Util{     /**      * Invert the endianness of words (4 bytes) in the given byte array       * starting at the given offset and repeating length/4 times.      * eg: b0b1b2b3 -> b3b2b1b0       *       * @param b the byte array       * @param offset the offset at which to change word start      * @param length the number of bytes on which to operate       * (should be a multiple of 4)      */     public final static void changeWordEndianess(byte[] b, int offset,             int length) {         byte tmp;         for (int i = offset; i < offset + length; i += 4) {             tmp = b[i];             b[i] = b[i + 3];             b[i + 3] = tmp;             tmp = b[i + 1];             b[i + 1] = b[i + 2];             b[i + 2] = tmp;         }     }     /**      * Invert two bytes in the given byte array starting at the given       * offset and repeating the inversion length/2 times.      * eg: b0b1 -> b1b0      *       * @param b the byte array       * @param offset the offset at which to change word start      * @param length the number of bytes on which to operate       * (should be a multiple of 2)      */     public final static void changeByteEndianess(byte[] b, int offset,             int length) {         byte tmp;         for (int i = offset; i < offset + length; i += 2) {             tmp = b[i];             b[i] = b[i + 1];             b[i + 1] = tmp;         }     } }