Java Integer to Byte Array integerToByteArray(int value)

Here you can find the source of integerToByteArray(int value)

Description

Take the given int value and convert it into a byte array suitable for sending over the network.

License

Open Source License

Declaration

public static final byte[] integerToByteArray(int value) 

Method Source Code

//package com.java2s;
/*/*  www .j  a  va2s  .c o m*/
 *   Copyright 2010 The Portico Project
 *
 *   This file is part of portico.
 *
 *   portico is free software; you can redistribute it and/or modify
 *   it under the terms of the Common Developer and Distribution License (CDDL) 
 *   as published by Sun Microsystems. For more information see the LICENSE file.
 *   
 *   Use of this software is strictly AT YOUR OWN RISK!!!
 *   If something bad happens you do not have permission to come crying to me.
 *   (that goes for your lawyer as well)
 *
 */

public class Main {
    /**
     * Take the given int value and convert it into a byte array suitable for sending over the
     * network. 
     */
    public static final byte[] integerToByteArray(int value) {
        return new byte[] { (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) (value) };
    }

    /**
     * Take the given int value and convert it into a byte array suitable for sending over the
     * network. This data is written into the provided buffer. If there is not enough room in
     * the buffer, a RuntimeException will be thrown.
     * 
     * @return The number of bytes written
     */
    public static final int integerToByteArray(int value, byte[] buffer, int offset) throws RuntimeException {
        if ((buffer.length - offset) < 4) {
            throw new RuntimeException("Not enough space in buffer to write int. Expected at "
                    + "least 4-bytes, found " + (buffer.length - offset));
        }

        buffer[offset] = (byte) (value >>> 24);
        buffer[offset + 1] = (byte) (value >>> 16);
        buffer[offset + 2] = (byte) (value >>> 8);
        buffer[offset + 3] = (byte) (value);

        return 4;
    }
}

Related

  1. int32toByteArray(int i)
  2. int32ToByteArray(int integer)
  3. int32ToByteArray(int value)
  4. integerToByteArray(final int integerToSerialize, final byte[] byteArray, final int offset)
  5. integerToByteArray(int a, byte[] buf)
  6. IntegerToBytes(int i, byte[] dst, int offset)
  7. integerToBytes(int v, byte[] b)
  8. integerToBytes(int v, byte[] b)
  9. integerToBytes(int value)