2011-06-16 88 views
59

可能重复:
Convert integer into byte array (Java)Java - 将int转换为4字节的Byte数组?

我需要存储一个缓冲区的长度,以字节数组4个字节大。

伪代码:

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; 
} 

什么是解决这个问题的最好方法?请记住,我必须稍后将该字节数组转换回整数。

+0

看看这个:http://stackoverflow.com/questions/5399798/byte-array-and-int-conversion-in-java – TacB0sS 2012-06-03 13:44:00

回答

109

您可以通过使用ByteBuffer这样的转换yourInt为字节:

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

当心,你可能有这样做的时候想想byte order

18

这应该工作:

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

代码taken from here

编辑更简单的解决方案是given in this thread

+0

你应该知道的顺序。在这种情况下,顺序是大端。从最重要到最不重要。 – Error 2016-07-07 16:45:58

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(); 
}