Here you can find the source of intToByteArray(final int x)
Parameter | Description |
---|---|
x | The integer |
public static byte[] intToByteArray(final int x)
//package com.java2s; /**/* ww w . j a v a 2s . co m*/ * Copyright (c) 2009-2011 National University of Ireland, Galway. All Rights Reserved. * * Project and contact information: http://www.siren.sindice.com/ * * This file is part of the SIREn project. * * SIREn is a free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * SIREn 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with SIREn. If not, see <http://www.gnu.org/licenses/>. */ public class Main { /** * Convert an integer to a byte array. * * @param x The integer * @return The byte array (length = 4) */ public static byte[] intToByteArray(final int x) { final byte[] bytes = new byte[4]; bytes[3] = (byte) (x & 0x000000ff); bytes[2] = (byte) ((x & 0x0000ff00) >>> 8); bytes[1] = (byte) ((x & 0x00ff0000) >>> 16); bytes[0] = (byte) ((x & 0xff000000) >>> 24); return bytes; } /** * Convert an integer to a byte array. * * @param x The integer * @param bytes The byte array (length = 4) */ public static final void intToByteArray(final int x, final byte[] bytes) { bytes[3] = (byte) (x & 0x000000ff); bytes[2] = (byte) ((x & 0x0000ff00) >>> 8); bytes[1] = (byte) ((x & 0x00ff0000) >>> 16); bytes[0] = (byte) ((x & 0xff000000) >>> 24); } /** * Convert an integer to a byte array. Copy 'length' integer bytes. * * @param x The integer * @param bytes The byte array * @param length The number of bytes to copy into the byte array */ public static final void intToByteArray(final int x, final byte[] bytes, final int length) { switch (length) { case 1: bytes[0] = (byte) (x & 0x000000ff); return; case 2: bytes[1] = (byte) (x & 0x000000ff); bytes[0] = (byte) ((x & 0x0000ff00) >>> 8); return; case 3: bytes[2] = (byte) (x & 0x000000ff); bytes[1] = (byte) ((x & 0x0000ff00) >>> 8); bytes[0] = (byte) ((x & 0x00ff0000) >>> 16); return; case 4: bytes[3] = (byte) (x & 0x000000ff); bytes[2] = (byte) ((x & 0x0000ff00) >>> 8); bytes[1] = (byte) ((x & 0x00ff0000) >>> 16); bytes[0] = (byte) ((x & 0xff000000) >>> 24); default: break; } } }