6

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?

3
  • what is the relation between i and str? Commented Apr 7, 2012 at 4:54
  • @dash1e, no relation. I just show an example. i and str are different. str is not i 's bit representation. Commented Apr 7, 2012 at 4:55
  • 1
    So you need two separate and fast function to convert intengers or bit string in byte array? Commented Apr 7, 2012 at 4:56

3 Answers 3

7

You can use the Java ByteBuffer class!

Example

byte[] bytes = ByteBuffer.allocate(4).putInt(1000).array();
Sign up to request clarification or add additional context in comments.

1 Comment

Is this available in java inbuilt packages ?
2

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.

Comments

1

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

2 Comments

The string can contain at most 32 bits (without leading zeros). And you need to put it in a byte array, so that's wrong
Ok, you need to process 8 bit per 8 bit, or reuse intToByteArray.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.