Java Convert via ByteBuffer toLittleEndian(int value)

Here you can find the source of toLittleEndian(int value)

Description

Convert the value using the little endian coding.

License

Open Source License

Declaration

public static byte[] toLittleEndian(int value) 

Method Source Code


//package com.java2s;
/*/*from ww  w.ja  v a  2s.  com*/
 * ByteUtils.java
 * 
 * Copyright (c) 2009-2013 Guillaume Mazoyer
 * 
 * This file is part of GNOME Split.
 * 
 * GNOME Split 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 3 of the License, or
 * (at your option) any later version.
 * 
 * GNOME Split 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 GNOME Split.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class Main {
    /**
     * Convert the value using the little endian coding.
     */
    public static byte[] toLittleEndian(int value) {
        ByteBuffer buffer = ByteBuffer.allocate(4);

        // Order as little endian and convert the value
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        buffer.putInt(value);

        return buffer.array();
    }

    /**
     * Convert the value using the little endian coding.
     */
    public static byte[] toLittleEndian(long value) {
        ByteBuffer buffer = ByteBuffer.allocate(8);

        // Order as little endian and convert the value
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        buffer.putLong(value);

        return buffer.array();
    }

    /**
     * Convert the value using the little endian coding and return only the 4
     * interesting bytes.
     */
    public static byte[] toLittleEndian(double value) {
        ByteBuffer buffer = ByteBuffer.allocate(8);

        // Order as little endian and convert the value
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        buffer.putDouble(value);

        // Keep only the 4 needed bytes
        byte[] result = buffer.array();
        result = new byte[] { result[4], result[5], result[6], result[7] };

        return result;
    }
}

Related

  1. toIntArray(byte[] byteArray)
  2. toIntArray(final byte[] byteArray)
  3. toIntArray(float[] floatArray)
  4. toIntBuffer(int[] array)
  5. toIntFromByteArray(byte[] byteArray)
  6. toLMBCS(final String value)
  7. toLong(byte data[])
  8. toLong(byte[] array)
  9. toLong(byte[] bytes)