Clark
Clark

Reputation: 3

Take the LSB of each int in an array and combine them to create a byte

So right now i have this

unsigned char getlsbs(unsigned char *p){
    int r;
    unsigned char newByte, temp;
    newByte = 0;

    for(r = 0; r < 8; r++){
            temp = p[r];
            temp &= -temp; // Gets the LSB of p[r]
            ((newByte & (1 << r)) >> r) |= temp; //This line does not work
    }
    return newByte;
}

for the line that doesn't work I am trying to set the rth int of newByte into the LSD so I can turn 00000000 into something like 10100001 any help would be greatly apreciated

Upvotes: 0

Views: 122

Answers (2)

Kev Bo
Kev Bo

Reputation: 172

A common way to accumulate bits into a target is to left shift in-place the previous value left, then OR in the new bit: newByte = (newByte << 1) | (temp & 0x01) In the above code, the left hand side of the line that says, "This line does not work" does not appear to be a valid target for an assignment operation.

Upvotes: 0

roeland
roeland

Reputation: 5741

You can't assign to an expression. To simplify the problem: a + 1 = b doesn't work. Rewrite that as a = b - 1 instead.

I would just do:

for(r = 0; r < 8; r++){
    newByte |= (p[r] & 1) >> r;
}

Upvotes: 1

Related Questions