gpt4 book ai didi

c - 屏蔽数组成员的位

转载 作者:行者123 更新时间:2023-11-30 21:19:53 25 4
gpt4 key购买 nike

你能告诉我我的问题出在哪里吗?我正在尝试测试数组的值。

每个值都呈现 16 位(标志),我需要检查标志是否已设置。

我当前的输出以及预期的输出如下所示。

 #include <stdio.h>

unsigned short value[1];
unsigned int bitCheck(unsigned int mask, int pin);
unsigned short mask;

int main(void){
value[0]=0;
value[1]=4095;


int pin0 = 0;
int pin1 = 1;

unsigned int bit0= bitCheck( mask, pin0);
unsigned int bit1= bitCheck( mask, pin1);


for (int i =0;i<=1; i++)
{
mask=value[i];
printf("Mask = %d ==>>\n", mask);

if ( bit0 == 1 ){
printf("Pin %d is Set\n", pin0);
}else{
printf("Pin %d is not Set\n", pin0);
}

if ( bit1 == 1 ){
printf("Pin %d is Set\n", pin1);
}else{
printf("Pin %d is not Set\n", pin1);
}

printf("\n");
}

}

unsigned int bitCheck(unsigned int mask, int bit){
if ( (mask >> bit ) & 1){
return 1;
}else{
return 0;
}
}

我的输出是:

Mask = 0 ==>>
Pin 0 is not Set
Pin 1 is not Set

Mask = 4095 ==>>
Pin 0 is not Set
Pin 1 is not Set

它必须是:

Mask = 0 ==>>
Pin 0 is not Set
Pin 1 is not Set

Mask = 4095 ==>>
Pin 0 is Set
Pin 1 is Set

最佳答案

此代码不必要地复杂,并且由于其复杂性,隐藏了一个公然逻辑错误。 mask 赋值之前,您需要调用 bitCheck(mask, ...)

更改此:

    unsigned int bit0= bitCheck( mask, pin0);
unsigned int bit1= bitCheck( mask, pin1);


for (int i =0;i<=1; i++)
{
mask=value[i];
printf("Mask = %d ==>>\n", mask);

对此:

  for (int i =0;i<=1; i++)
{
mask=value[i];

unsigned int bit0= bitCheck( mask, pin0);
unsigned int bit1= bitCheck( mask, pin1);

printf("Mask = %d ==>>\n", mask);
<小时/>

也就是说,这是一个理智的方法来完成这一切:

#include <stdio.h>

#define BIT(n, v) (!!((v) & (1U << (n))))

int main(void)
{
unsigned short values[] = {0, 4095};
for (int i = 0; i < 2; ++i)
{
printf("value: %hu\n", values[i]);
for (int bit = 0; bit < 16; ++bit)
{
printf( BIT(bit, values[i]) ?
"bit %d is set\n" :
"bit %d is not set\n", bit);
}
}
return 0;
}

由于您的方法被认为不明智的原因之一,请阅读 DRY principle 。编写 16 次相同的代码就是违反此原则的一个简单示例 -> 您需要一个循环。

关于c - 屏蔽数组成员的位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45727666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com