Java examples for java.lang:byte Array Convert
Convert int to byte array
/**//from w w w.j a va 2 s . co m * Syncnapsis Framework - Copyright (c) 2012-2014 ultimate * * 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 * 3 of the License, or 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 MECHANTABILITY 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 Plublic License along with this program; * if not, see <http://www.gnu.org/licenses/>. */ //package com.java2s; public class Main { public static void main(String[] argv) throws Exception { int data = 2; System.out.println(java.util.Arrays.toString(toByteArray(data))); } /** * Convert int to byte array * * @param data - the int value * @return the byte array */ public static byte[] toByteArray(int data) { // @formatter:off return new byte[] { (byte) ((data >> 24) & 0xff), (byte) ((data >> 16) & 0xff), (byte) ((data >> 8) & 0xff), (byte) ((data >> 0) & 0xff) }; // @formatter:on } /** * Convert long to byte array * * @param data - the long value * @return the byte array */ public static byte[] toByteArray(long data) { // @formatter:off return new byte[] { (byte) ((data >> 56) & 0xff), (byte) ((data >> 48) & 0xff), (byte) ((data >> 40) & 0xff), (byte) ((data >> 32) & 0xff), (byte) ((data >> 24) & 0xff), (byte) ((data >> 16) & 0xff), (byte) ((data >> 8) & 0xff), (byte) ((data >> 0) & 0xff) }; // @formatter:on } /** * Convert float to byte array * * @param data - the float value * @return the byte array */ public static byte[] toByteArray(float data) { return toByteArray(Float.floatToRawIntBits(data)); } /** * Convert double to byte array * * @param data - the double value * @return the byte array */ public static byte[] toByteArray(double data) { return toByteArray(Double.doubleToRawLongBits(data)); } /** * Convert boolean to byte array * * @param data - the boolean value * @return the byte array */ public static byte[] toByteArray(boolean data) { return new byte[] { (byte) (data ? 0x01 : 0x00) }; } }