2012-04-07 54 views
6

我有一個字符串,它包含一系列位(如「01100011」)和while循環中的一些整數。例如:Java字節數組轉換問題

while (true) { 
    int i = 100; 
    String str = Input Series of bits 

    // Convert i and str to byte array 
} 

現在我想要一個很好的最快方法來將字符串和int轉換爲字節數組。到目前爲止,我所做的是將int轉換爲String,然後在兩個字符串上應用getBytes()方法。但是,它有點慢。有沒有其他方法可以做到這一點(可能)比這更快?

+0

是什麼i'和'str''之間的關係? – dash1e 2012-04-07 04:54:15

+0

@ dash1e,沒有關係。我只是舉一個例子。我和str是不同的。 str不是我的比特表示。 – Arpssss 2012-04-07 04:55:57

+1

所以你需要兩個獨立的快速函數來轉換字節數組中的整數或位串? – dash1e 2012-04-07 04:56:52

回答

7

您可以使用Java ByteBuffer類!

byte[] bytes = ByteBuffer.allocate(4).putInt(1000).array(); 
+0

這是在java內置包中可用嗎? – Arpssss 2012-04-07 05:12:31

+0

非常感謝。我找到了。 – Arpssss 2012-04-07 05:16:53

+0

@Arpssss np。好友 – Kevin 2012-04-07 05:17:28

2

轉換一個int是容易的(小端):

byte[] a = new byte[4]; 
a[0] = (byte)i; 
a[1] = (byte)(i >> 8); 
a[2] = (byte)(i >> 16); 
a[3] = (byte)(i >> 24); 

轉換字符串,第一轉換與Integer.parseInt(s, 2)爲整數,則執行上面。如果您的位串可能高達64位,則使用Long;如果它比這更大,則使用BigInteger

1

對於INT

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

對於字符串

byte[] buf = intToByteArray(Integer.parseInt(str, 2)) 
+0

對於字符串方法不起作用。 – Rushil 2012-04-07 06:45:41

+0

你的字符串有多長? – dash1e 2012-04-07 06:46:32

+1

該字符串最多可以包含32位(不含前導零)。你需要把它放在一個字節數組中,所以這是錯誤的 – Rushil 2012-04-07 07:52:56