Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Byte Array conversion Issue

Tags:

java

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?

like image 715
Arpssss Avatar asked Apr 07 '12 04:04

Arpssss


3 Answers

You can use the Java ByteBuffer class!

Example

byte[] bytes = ByteBuffer.allocate(4).putInt(1000).array();
like image 104
Kevin Avatar answered Nov 06 '22 19:11

Kevin


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.

like image 22
Keith Randall Avatar answered Nov 06 '22 18:11

Keith Randall


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))
like image 33
dash1e Avatar answered Nov 06 '22 18:11

dash1e