Bitwise Operations on char*

groove picture groove · Jan 23, 2013 · Viewed 12.6k times · Source

GCC gives error when compiling the code below. The commented two lines instead of the other or and shift lines work, but I'm not sure if the castings are necessary and true.

The error is this: invalid operands to binary | (have 'char*' and 'int')

Thanks.

void bits2byte(int *bits, char *byte) {
    byte = 0;
    int i;
    for (i = 0; i<8; i++) {
        if (bits[i] == 1) {
            byte = byte | 0x01;
            // byte = (char*)((int)byte | 0x01);
        }
        if (i<7) {
            byte = byte << 0x01;
            // byte = (char*)((int)byte << 0x01);
        }
    }
}
int main() {
    int input_bits[] = {1, 1, 0, 1, 0, 0, 1, 1};
    char output_byte;
    bits2byte(input_bits, &output_byte);
}

Edit: I understand that this is a pass-by-reference problem. I'm trying to modify the byte. I want the function to convert bits into a byte. Actually I've first written it in the way all the answerers/commenters suggest, but the pass by reference example in http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fcplr233.htm confused my mind.

Answer

unwind picture unwind · Jan 23, 2013

Why are you doing bitwise operations on a pointer? That's not a good idea, which is why you're getting compiler errors.

You need to dereference the pointer with * to get a value that you can do these operations on:

*byte |= 1;

or

*byte <<= 1;

Note use of |= and <<= operators to make the code simpler, this is even more useful when working through pointers since the "target" expression is longer than for a direct variable.