7 Replies Latest reply on Dec 5, 2008 3:55 PM by 807589

# Getting subset of bits from int array and form byte array

I would like to have write a method in Java with following signature:
public byte[] extractBytes(int[] input);

Argument to the method is an array of 32 ints. As int in Java is 32 bits, we are providing 1024 bits of input.

I want the method to return an array of 107 bytes (856 bits), where the bytes start from 85 th bit(including) of input and end at 938 bit (including) of input - 854 bits. The 2 LSBs of the 107th byte are unsed.

Can I please have solution ?
• ###### 1. Re: Getting subset of bits from int array and form byte array
Hello and welcome to the Sun Java forums.

What have you tried as of this writing? And where does it fail?

s
• ###### 2. Re: Getting subset of bits from int array and form byte array
Thank you for the welcome. Here is what I have so far :

public static byte[] convert(int [] input){

byte[] output = new byte[107];

// 4 bytes per int; as input has 32 ints, hence, 128
byte[] temp = new byte[128];

for (int i = 0; i < input.length; i++)
{
temp[i*4] = (byte)(input[i] >>> 24);
temp[i*4+1] = (byte)(input[i] >>> 16);
temp[i*4+2] = (byte)(input[i] >>> 8);
temp[i*4+3] = (byte)(input);
}

return output;
}

I want the method to return an array of 107 byte, where the byte position starts from 85 th bit of 'temp' byte array that was produced in the method and end at 938 bit of 'temp' byte array. Do not know how to do.

Any help is appreciated.
• ###### 3. Re: Getting subset of bits from int array and form byte array
Will this work ?

public byte[] convert(int[] input) {

byte[] target = new byte[107];

// 4 bytes per int; as input has 32 ints, hence, 128
byte[] temp = new byte[128];

for (int i = 0; i < input.length; i++)
{
temp[i*4] = (byte)(input[i] >>> 24);
temp[i*4+1] = (byte)(input[i] >>> 16);
temp[i*4+2] = (byte)(input[i] >>> 8);
temp[i*4+3] = (byte)(input);
}

for (int i = 10; i < 117; i++)
{
target[i-10] = (byte) (temp[i] << 6);
target[i-10] |= (byte) (temp[i+1] >> 2) & 0x3F;

}

return target;
}
• ###### 4. Re: Getting subset of bits from int array and form byte array
I think it is close enough that you should test it.

After you take into account
KrisAZ wrote:
The 2 LSBs of the 107th byte are unsed.
• ###### 5. Re: Getting subset of bits from int array and form byte array
Thank you. "The 2 LSBs of the 107th byte are unsed" means they can be with 1's or 0's right ?
Is my assumption valid ?.

Thank you.
• ###### 6. Re: Getting subset of bits from int array and form byte array
KrisAZ wrote:
"The 2 LSBs of the 107th byte are unsed" means they can be with 1's or 0's right ?
How do I know - I was quoting you - surely you know what you meant.
• ###### 7. Re: Getting subset of bits from int array and form byte array
Thank you all for the help