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
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
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.
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
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.