Reputation: 283
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.
Upvotes: 1
Views: 17648
Reputation: 19443
That's what you are trying to do (I think)
void bits2byte(int *bits, char *byte) {
//notice ALL the work is with "*byte" not "byte" which is the address of the byte.
*byte = 0;
for (int i = 0; i < 8; i++) {
*byte <<= 1;
if (bits[i] == 1) {
*byte |= 1;
}
}
}
int main() {
int input_bits[] = {1, 1, 0, 1, 0, 0, 1, 1};
char output_byte; //no use to put value here, we'll override it anyway...
bits2byte(input_bits, &output_byte);
}
Upvotes: 1
Reputation: 23707
The C standard states that the operand of such operators shall have scalar type.
C11 (n1570), § 6.5.14 Logical OR operator
Each of the operands shall have scalar type.
You can cast to intptr_t
(C99/C11).
#include <stdint.h>
intptr_t n = (void *)byte;
Anyway, it is hard to say what you are trying to do. Don't you want to do this operations on the value pointed by the pointer? In such case, you have to dereference it.
*byte = *byte | 0x01;
Upvotes: 2
Reputation: 399949
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.
Upvotes: 5