Java Integer to Byte Array intToBytes(final int aInt)

Here you can find the source of intToBytes(final int aInt)

Description

int To Bytes

License

Open Source License

Parameter

Parameter Description
aInt a parameter

Declaration

public static byte[] intToBytes(final int aInt) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2011 www.isandlatech.com (www.isandlatech.com)
 * 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://from  w w w .ja va 2s .  c  o  m
 *    ogattaz (isandlaTech) - initial API and implementation
 *******************************************************************************/

public class Main {
    public static final int LEN_OF_INT = 4;
    private static final String MESS_NOT_ENOUGH_LARGE = "The byte array is not enough large. It should have at least [%s] bytes to accept an [%s]";

    /**
     * @param aInt
     * @return
     */
    public static byte[] intToBytes(final int aInt) {
        byte[] wBuffer = new byte[LEN_OF_INT];
        appendIntInBuffer(wBuffer, 0, aInt);
        return wBuffer;
    }

    /**
     * Ajoute un "entier" 4 octets au buffer.
     * 
     * @return la nouvelle position
     * @param aBuffer
     * @param aPos
     * @param aValue
     * @return la nouvelle position
     * @throws IllegalArgumentException
     */
    public static int appendIntInBuffer(final byte[] aBuffer,
            final int aPos, final int aValue)
            throws IllegalArgumentException {
        if (aBuffer.length - aPos < LEN_OF_INT) {
            throw new IllegalArgumentException(builNotEnoughLargeMess(
                    LEN_OF_INT, "int"));
        }

        for (int i = 3; i >= 0; i--) {
            aBuffer[aPos + 3 - i] = (byte) (aValue >>> (8 * i));
        }
        return aPos + LEN_OF_INT;
    }

    /**
     * @param aSize
     * @param aContent
     * @return
     */
    private static String builNotEnoughLargeMess(final int aSize,
            final String aContent) {
        return String.format(MESS_NOT_ENOUGH_LARGE, String.valueOf(aSize),
                aContent);
    }
}

Related

  1. intToByteArrayLE(int v)
  2. intToByteLittleEnding(int j)
  3. intToByteMSB(int in)
  4. intToBytes(byte[] arr, int offset, int num)
  5. intToBytes(byte[] bytes, int index, int value)
  6. intToBytes(final int i)
  7. intToBytes(final int integer, final int bLength)
  8. intToBytes(final int number)
  9. intToBytes(final int value)