My task is to write a macro that checks how many elements in an array of INTs has excatly 5 bits that are on.
I know a macro is a very risky way of doing it, but that is the question that appears in some exams.
This is my code:
#include <stdio.h>
#define RESULT 5
#define SIZE 8
#define BITW(arr, length, counter)\
int mask=0b00000001, bits=0, i=0, j=0;\
for (i=0; i<length; i++){\
for (j=0; j<sizeof(arr[i])*SIZE; j++){\
if(mask&arr[i]>>j)\
bits++;\
}\
if (bits==RESULT)\
counter++;\
}
int main(void){
int arr[4]={0b11111000,0b11100011,0b11001100,0b11000000};
int res=0; int counter=0;
BITW(arr, 4, counter);
printf("%d",counter);
}
The problem with macros is that I can't debug my code. I went over it a few times with no success but I realized I got the result 1 instead of 2.
The counter variable is the one that counts how many elements has 5 bits on. The bit variable counts in a certain element how many bits are on.
Thank you for your help.