Reputation: 17
The following is a method(public static byte[] bitStuff(byte[] b)) for bit stuffing of a message in java. But I can't understand the lines commented out inside the method:
public static byte set_1_at_position(int i, byte b) {
b |= (128 >> i);
return b;
}
public static byte set_0_at_position(int i, byte b) {
b &= (byte) (~(128 >> i));
return b;
}
public static int get_bit_at_position(int pos, byte b) {
if ((b & (byte) (128 >> pos)) == 0) {
return 0;
}
return 1;
}
public static byte[] bitStuff(byte[] b){
byte[] temp=new byte[b.length*2];
int size=b.length*8;
int count_of_one=0;
int count_of_temp=0;
for(int i=0;i<size;i++)
{
int bit=get_bit_at_position(i%8, b[i/8]); //what is being done here
if(bit==1)
{
count_of_one++;
temp[count_of_temp/8]=set_1_at_position(count_of_temp%8, temp[count_of_temp/8]); //what is happening in this line
}
else
{
count_of_one=0;
temp[count_of_temp/8]=set_0_at_position(count_of_temp%8, temp[count_of_temp/8]);
}
count_of_temp++;
if(count_of_one==5)
{
count_of_one=0;
//bit stuffing
temp[count_of_temp/8]=set_0_at_position(count_of_temp%8, temp[count_of_temp/8]); // what is happening in this line
count_of_temp++;
}
}
byte[] ret=new byte[(count_of_temp+7)/8];
System.arraycopy(temp, 0, ret, 0, ret.length);
return ret;
}
can anyone explain these lines?
Upvotes: 0
Views: 54
Reputation: 53
Note that the "size" and "i" variables, are counting the bits (not bytes). get_bit_at_position(i%8, b[i/8]); This line returns the "i"th bit value. The "i"th bit value is equivalent to the "i%8"th bit value at the "i/8"th byte. set_0_at_position(count_of_temp%8, temp[count_of_temp/8]); This is almost the inverse of the above line. It sets the "i"th bit to zero.
Upvotes: 1