2011-06-16 94 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(); 
}