一个宏数是位上(设定)的(a macro to count bits that are on (se

2019-10-19 08:45发布

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.

Answer 1:

宏置位失败bits中的每个数组元素计数位之前为零。 它设置bits只在循环的整个阵列上之前为零。



Answer 2:

我可能会做这样的事情,如果你真的想要一个宏:

static const int bits_per_nibble[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 };
#define BITS_PER_U8(x) (bits_per_nibble[(x) & 0xf] + bits_per_nibble[((x) >> 4) & 0xf])
#define BITS_PER_U16(x) (BITS_PER_U8((x) & 0xff) + BITS_PER_U8(((x) >> 8) & 0xff))
#define BITS_PER_U32(x) (BITS_PER_U16((x) & 0xffff) + BITS_PER_U16(((x) >> 16) & 0xffff))

定义BITS_PER_U64应该是一个明显的扩展,如果它的需要。

但是,这样做的一个小的内联函数会被很多更安全,更好的解决方案?

还有这个 ,这对方式来获得以各种方式“人口数”一整节...



Answer 3:

我说

 if(mask&arr[i]>>j)\ bits++;\ 

是错误的,因为它测试,如果结果中的任何位被置位,如果不是所有的人都设定。 我已经重写了代码来计数1个字节的位数

 bits=0; for (mask=0b10000000; mask!=0; mask=mask>>1) if (arr[i]&mask) bits++; if (bits==5) ... 

注意:如果面膜是无符号或有超过8位这只适用,因此char不会>做(你的int是OK虽然)。

但这是错误的。

然而,

#define BITW(arr, length, counter)\
int mask=0b00000001, bits=0, i=0, j=0;\
for (i=0; i<length; i++){\
    bits=0;                         //<---- This line is missing from your code
    for (j=0; j<sizeof(arr[i])*SIZE; j++){\
        if(mask&arr[i]>>j)\
            bits++;\
    }\
    if (bits==RESULT)\
        counter++;\
}

不重置位,每个字节计数器。

要调试宏,第一个,写你可以调试的功能; 那么,当你确定它的工作原理,功能转换为宏。



Answer 4:

主要问题已经由Eric回答。

用宏的问题是,我不能调试我的代码。

你可以利用的printf的的宏,或者你可以用替换在宏代码段宏调用。



文章来源: a macro to count bits that are on (set)