繁体   English   中英

Java 字节数组转换问题

[英]Java Byte Array conversion Issue

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

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

    // Convert i and str to byte array
}

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

您可以使用Java ByteBuffer类!

例子

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

转换 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)转换为 integer,然后执行上述操作。 如果您的位串可能高达 64 位,则使用Long ,如果它比这更大,则使用BigInteger

对于整数

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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM