Java Integer to Byte Array intToByteArray(int piValueToConvert, boolean pbBigEndian)

Here you can find the source of intToByteArray(int piValueToConvert, boolean pbBigEndian)

Description

Converts an int value to a byte array.

License

Open Source License

Parameter

Parameter Description
piValueToConvert the original integer
pbBigEndian true if the bytes are in Big-endian order; false otherwise

Return

byte[] representation of the int

Declaration

public static byte[] intToByteArray(int piValueToConvert, boolean pbBigEndian) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//w w  w . j  a v a  2 s .  c o m
     * Converts an int value to a byte array.
     *
     * @param piValueToConvert the original integer
     * @param pbBigEndian true if the bytes are in Big-endian order; false otherwise
     *
     * @return byte[] representation of the int
     */
    public static byte[] intToByteArray(int piValueToConvert, boolean pbBigEndian) {
        byte[] aRetVal = new byte[4];

        byte iLowest;
        byte iLow;
        byte iMid;
        byte iHigh;

        iLowest = (byte) (piValueToConvert & 0xFF);
        iLow = (byte) ((piValueToConvert >> 8) & 0xFF);
        iMid = (byte) ((piValueToConvert >> 16) & 0xFF);
        iHigh = (byte) ((piValueToConvert >> 24) & 0xFF);

        if (pbBigEndian) {
            aRetVal[3] = iLowest;
            aRetVal[2] = iLow;
            aRetVal[1] = iMid;
            aRetVal[0] = iHigh;
        } else {
            aRetVal[0] = iLowest;
            aRetVal[1] = iLow;
            aRetVal[2] = iMid;
            aRetVal[3] = iHigh;
        }

        return aRetVal;
    }
}

Related

  1. intToByteArray(int i)
  2. intToByteArray(int i)
  3. intToByteArray(int input)
  4. intToByteArray(int integer)
  5. intToByteArray(int integer)
  6. intToByteArray(int pSrc, byte[] pDst, int pOffset)
  7. intToByteArray(int source)
  8. IntToByteArray(int val, byte[] buf, int offset)
  9. intToByteArray(int value)