简体   繁体   中英

Java Byte Array conversion Issue

I have a string which contains a series of bits (like "01100011") and some Integers in a while loop. For example:

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

    // Convert i and str to byte array
}

Now I want a nice fastest way to convert string and int to byte array. Until now, what I have done is convert int to String and then apply the getBytes() method on both strings. However, it is little bit slow. Is there any other way to do that which is (may be) faster than that?

You can use the Java ByteBuffer class!

Example

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

Converting an int is easy (little endian):

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

Converting the string, first convert to integer with Integer.parseInt(s, 2) , then do the above. Use Long if your bitstring may be up to 64 bits, and BigInteger if it will be even bigger than that.

For int

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

For string

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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