hi,

I've got a really long String of bits,
like: "0010101011101010011011011010100110101010110101..."
And I want to chop it into pieces of eight and make
bytes out of them, in an array.
what would be a performant way to do this?
Thanks

Ephron

Edited 5 Years Ago by Ephron: n/a

Unless you have truely gigantic strings arriving a high rate per second then performance is unlikely to be an issue. Much better to find a clear and obvious way to code it, and only worry about performance if it becomes a problem.
Just convert to a char array, then take each char in each block of 8 one at a time and set the corresponding bit of the output byte.

thanks a lot so far,
but em, I'm a bit of an newbee when it comes to bytes,
could you show me how to set those bits?
thanks

Use the bitwise OR operator to set a bit in a byte.

byte x = 0;
      x = (byte)(x | 1);    // set the low order bit
      x = (byte)(x | 0x80); // set the high order bit
      System.out.println("x=" + x + " " + Integer.toHexString((0xFF) & x));  // AND to strip sign bits

You will probably have problems with the compiler trying to make everything into an int. You can Use casting to solve some problems.

Edited 5 Years Ago by NormR1: n/a

hi,

I searched around a bit and found this site:
http://www.exampledepot.com/egs/java.util/Bits2Array.html

so this is how I finally did it:

private byte[] toByteArray(String input)
{
    //to charArray
    char[] preBitChars = input.toCharArray();
    int bitShortage = (8-(preBitChars.length%8));
    char[] bitChars = new char[preBitChars.length+bitShortage];
    System.arraycopy(preBitChars, 0, bitChars, 0, preBitChars.length);
    for (int  i= 0;  i < bitShortage;  i++)
    {
        bitChars[preBitChars.length+i]='0';
    }
    //to bytearray
    byte[] byteArray = new byte[bitChars.length/8];
    for(int i=0; i<bitChars.length; i++)
    {
        if (bitChars[i]=='1')
        {
            byteArray[byteArray.length - (i/8) - 1] |= 1<<(i%8);
        }
    }
    return byteArray;
}

thanks for all the help.

Ephron

This article has been dead for over six months. Start a new discussion instead.