Java Convert via ByteBuffer toByteArray(int i)

Here you can find the source of toByteArray(int i)

Description

to Byte Array

License

Open Source License

Declaration

public static byte[] toByteArray(int i) 

Method Source Code

//package com.java2s;
/*//from  w  w  w  .ja  va 2  s. c om
 * ******************************************************************************
 *  Copyright (c) 2013-2014 CriativaSoft (www.criativasoft.com.br)
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  which accompanies this distribution, and is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 *
 *  Contributors:
 *  Ricardo JL Rufino - Initial API and Implementation
 * *****************************************************************************
 */

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

public class Main {
    public static byte[] toByteArray(int i) {
        final ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE);
        bb.order(ByteOrder.LITTLE_ENDIAN);
        bb.putInt(i);
        return bb.array();
    }

    public static byte[] toByteArray(int[] values) {
        final ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE);
        bb.order(ByteOrder.LITTLE_ENDIAN);
        for (int i : values) {
            bb.putInt(i);
        }
        return bb.array();
    }

    public static byte[] toByteArray(long i) {
        final ByteBuffer bb = ByteBuffer.allocate(Long.SIZE / Byte.SIZE);
        bb.order(ByteOrder.LITTLE_ENDIAN);
        bb.putLong(i);
        return bb.array();
    }

    public static byte[] toByteArray(long[] values) {
        final ByteBuffer bb = ByteBuffer.allocate(Long.SIZE / Byte.SIZE);
        bb.order(ByteOrder.LITTLE_ENDIAN);
        for (long i : values) {
            bb.putLong(i);
        }
        return bb.array();
    }
}

Related

  1. toByteArray(char[] chars)
  2. toByteArray(double value)
  3. toByteArray(double[] doubleArray)
  4. toByteArray(float[] floatArray)
  5. toByteArray(InputStream input, boolean nioCopy)
  6. toByteArray(int integer)
  7. toByteArray(int value)
  8. toByteArray(int value)
  9. toByteArray(int[] data, boolean bigEndian)