你能告诉我我的问题在哪里吗?我正在尝试测试数组的值。
每个值都有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
答案 0 :(得分:2)
此代码不必要地复杂,并且由于其复杂性,隐藏了明显的逻辑错误。您之前在bitCheck(mask, ...)
之前拨打电话,您已将值分配给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次相同的代码是违反这一原则的一个简单例子 - &gt;你需要一个循环。