I'm trying to write a function that receives a char* pointer and an index and checks whether the bit in the index is on.
i got somthing like that:
int bitIsOn(char *ptr, int index){
return (ptr[index/8] & (1<< (index%8)));
}
note: I need to use c90. I am getting the following error message: error: invalid operands to binary & (have 'char *' and 'int')
How can I avoid type collision here
CodePudding user response:
Use unsigned data for bitwise operations. Use standard definition CHAR_BIT
instead of magic number 8 (it is defined in limits.h
header file).
int checkbit(const void *data, const size_t index)
{
const unsigned char *udata = data;
return udata[index / CHAR_BIT] & (1 << (index % CHAR_BIT));
}
If you want to return 0
or 1
you can use double logical NOT
operator:
return !!(udata[index / CHAR_BIT] & (1 << (index % CHAR_BIT)));