一个宏,用于对置位(设置)的位进行计数 [英] a macro to count bits that are on (set)

查看:192
本文介绍了一个宏,用于对置位(设置)的位进行计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务是编写一个宏,检查一个INT数组中有多少个元素具有5个以上处于打开状态的宏.

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.

这是我的代码:

#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);


}

宏的问题是我无法调试代码.我经过了几次都没有成功,但我意识到我得到的结果是1而不是2.

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.

计数器变量是一个计数多少元素具有5位的变量.位变量在某个元素中计算打开了多少位.

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.

谢谢您的帮助.

推荐答案

在对每个数组元素中的位进行计数之前,宏无法将bits设置为零.只能在循环遍历整个数组之前将bits设置为零.

The macro fails to set bits to zero before counting the bits in each array element. It sets bits to zero only before the loop over the entire array.

这篇关于一个宏,用于对置位(设置)的位进行计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆