Here you can find the source of toBytes(int i)
Parameter | Description |
---|---|
i | An integer value. |
public static byte[] toBytes(int i)
//package com.java2s; /*/* w w w . j ava 2s . c om*/ * Copyright (c) 2015 NEC Corporation * 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 */ public class Main { /** * The number of octets in an integer value. */ public static final int NUM_OCTETS_INTEGER = Integer.SIZE / Byte.SIZE; /** * The number of bits to be shifted to get the first octet in an integer. */ private static final int INT_SHIFT_OCTET1 = 24; /** * The number of bits to be shifted to get the second octet in an integer. */ private static final int INT_SHIFT_OCTET2 = 16; /** * The number of bits to be shifted to get the third octet in an integer. */ private static final int INT_SHIFT_OCTET3 = 8; /** * Convert an integer value into an byte array. * * @param i An integer value. * @return A converted byte array. */ public static byte[] toBytes(int i) { byte[] b = new byte[NUM_OCTETS_INTEGER]; setInt(b, 0, i); return b; } /** * Set an integer value into the given byte array in network byte order. * * @param array A byte array. * @param off Index of {@code array} to store value. * @param value An integer value. */ public static void setInt(byte[] array, int off, int value) { int index = off; array[index++] = (byte) (value >>> INT_SHIFT_OCTET1); array[index++] = (byte) (value >>> INT_SHIFT_OCTET2); array[index++] = (byte) (value >>> INT_SHIFT_OCTET3); array[index] = (byte) value; } }