2012-04-07 89 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