2011-06-16 12 views
59

संभव डुप्लिकेट:
Convert integer into byte array (Java)जावा - 4 बाइट्स के बाइट ऐरे में int को कनवर्ट करें?

मैं, एक बफर की लंबाई स्टोर करने के लिए एक बाइट सरणी 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

उत्तर

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

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(); 
} 
संबंधित मुद्दे