Java examples for java.lang:byte Array Convert
Convert an integer to a byte array.
/*/*from w ww. j a v a2 s .c o m*/ * @(#) ByteArrayUtils.java * * This code is part of the JAviator project: javiator.cs.uni-salzburg.at * Copyright (c) 2009 Clemens Krainer * * 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 2 of the License, or * (at your option) 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 * 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 this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ //package com.java2s; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; public class Main { public static void main(String[] argv) throws Exception { int i = 2; System.out.println(java.util.Arrays.toString(int2bytes(i))); } /** * Convert an integer to a byte array. * * @param i the integer number to be converted. * @return the integer represented as a byte array. * @throws IOException thrown in case of conversion errors. */ public static byte[] int2bytes(int i) throws IOException { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DataOutputStream dOut = new DataOutputStream(bOut); dOut.writeInt(i); return bOut.toByteArray(); } }