2011-06-16 38 views
59

Duplicar posible:
Convert integer into byte array (Java)Java - ¿Convertir int a Byte Array de 4 bytes?

necesito para almacenar la longitud de un tampón, en una matriz de bytes 4 bytes grande.

pseudo código:

private byte[] convertLengthToByte(byte[] myBuffer) 
{ 
    int length = myBuffer.length; 

    byte[] byteLength = new byte[4]; 

    //here is where I need to convert the int length to a byte array 
    byteLength = length.toByteArray; 

    return byteLength; 
} 

¿Cuál sería la mejor manera de lograr esto? Teniendo en cuenta que debo convertir esa matriz de bytes a un número entero más tarde.

+0

Tome un vistazo a esto: http://stackoverflow.com/questions/5399798/byte-array-and-int-conversion-in-java – TacB0sS

Respuesta

109

Puede convertir yourInt de bytes mediante el uso de un ByteBuffer así:

return ByteBuffer.allocate(4).putInt(yourInt).array(); 

Tenga en cuenta que puede que tenga que pensar en el byte order antes de hacerlo.

18

Esto debería funcionar:

public static final byte[] intToByteArray(int value) { 
    return new byte[] { 
      (byte)(value >>> 24), 
      (byte)(value >>> 16), 
      (byte)(value >>> 8), 
      (byte)value}; 
} 

Código taken from here.

Editar Una solución aún más simple es given in this thread.

+0

usted debe estar al tanto de orden. en ese caso, el orden es big endian. de lo más significativo a lo menos. – Error

18
int integer = 60; 
byte[] bytes = new byte[4]; 
for (int i = 0; i < 4; i++) { 
    bytes[i] = (byte)(integer >>> (i * 8)); 
} 
35
public static byte[] my_int_to_bb_le(int myInteger){ 
    return ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(myInteger).array(); 
} 

public static int my_bb_to_int_le(byte [] byteBarray){ 
    return ByteBuffer.wrap(byteBarray).order(ByteOrder.LITTLE_ENDIAN).getInt(); 
} 

public static byte[] my_int_to_bb_be(int myInteger){ 
    return ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(myInteger).array(); 
} 

public static int my_bb_to_int_be(byte [] byteBarray){ 
    return ByteBuffer.wrap(byteBarray).order(ByteOrder.BIG_ENDIAN).getInt(); 
}