Convert a short value to littleEndian - Java java.lang

Java examples for java.lang:int Format

Description

Convert a short value to littleEndian

Demo Code

/*/*from   w  w  w . j  a  v  a  2  s.  co m*/

(C) Copyright 2015-2016 Alberto Fern?ndez <infjaf@gmail.com>
(C) Copyright 2014 Jan Schl??in
(C) Copyright 2003-2004 Anil Kumar K <anil@linuxense.com>

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.

This library 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
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library.  If not, see <http://www.gnu.org/licenses/>.

 */
//package com.java2s;

public class Main {
    /**
     * Convert a short value to littleEndian
     * @param value value to be converted
     * @return littleEndian short
     */
    public static short littleEndian(short value) {

        short num1 = value;
        short mask = (short) 0xff;

        short num2 = (short) (num1 & mask);
        num2 <<= 8;
        mask <<= 8;

        num2 |= (num1 & mask) >> 8;

        return num2;
    }

    /**
     * Convert an int value to littleEndian
     * @param value value to be converted
     * @return littleEndian int
     */
    public static int littleEndian(int value) {

        int num1 = value;
        int mask = 0xff;
        int num2 = 0x00;

        num2 |= num1 & mask;

        for (int i = 1; i < 4; i++) {
            num2 <<= 8;
            mask <<= 8;
            num2 |= (num1 & mask) >> (8 * i);
        }

        return num2;
    }
}

Related Tutorials