Java字节数组转换问题

时间:2012-04-07 04:49:43

标签: java

我有一个字符串,其中包含一系列位(如“01100011”)和一些while循环中的整数。例如:

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

    // Convert i and str to byte array
}

现在我想要一种将字符串和int转换为字节数组的最快方法。到目前为止,我所做的是将int转换为String,然后在两个字符串上应用getBytes()方法。但是,它有点慢。有没有其他方法可以做到(可能)比那更快?

3 个答案:

答案 0 :(得分:7)

您可以使用Java ByteBuffer类!

实施例

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

答案 1 :(得分: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

答案 2 :(得分: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))
相关问题