3

在一个字节中,我设置了一些位 |视频 | 音频 | 扬声器 | 麦克风 | 耳机 | 带位 LED |1 | 1 | 1 | 3 | 1 | 1
1 个字节,麦克风除外,麦克风有 3 个字节,因此可以有 7 个组合,离开第一个组合。

#define Video    0x01
#define Audio    0x02
#define Speaker     0x04
#define MicType1  0x08 
#define MicType2  0x10
#define MicType3  0x20
#define MicType4 (0x08 | 0x10) 
#define MicType5 (0x08 | 0x20)
#define MicType6 (0x10 | 0x20)
#define MicType7 ((0x08 | 0x10) | 0x20)
#define HeadPhone 0x40
#define Led    0x80

现在我设置位

MySpecs[2] |= (1 << 0);
MySpecs[2] |= (1 << 2);

//设置mictype6

MySpecs[2] |= (1 << 4);
MySpecs[2] |= (1 << 5);

当我读到这样

 readCamSpecs()
    {
        if(data[0] &  Video)
            printf("device with Video\n");
        else
            printf("device with no Video\n");
        if(data[0] & Audio) 
            printf("device with Audio\n");
        else
            printf("device with no Audio\n");

        if(data[0] & Mictype7)
            printf("device with Mictype7\n");
        if(data[0] & Mictype6)
            printf("device with Mictype6\n");
    }

用单个位设置的值,它可以找到。但是用多个位设置的值(例如,MicType5,6,7)会出错并显示第一个检查的值。我究竟做错了什么?

4

4 回答 4

2

即使只设置了一位,您的&检查也会成功,因为结果仍然是非零的。

试试if ( data[0] & Mictype7 == MicType7 )吧。

于 2012-08-01T07:18:25.267 回答
2

试试这个:

#define MicTypeMask (0x08 | 0x10 | 0x20)


if((data[0] & MicTypeMask) == Mictype7)
    printf("device with Mictype7\n");
if((data[0] & MicTypeMask) == Mictype6)
    printf("device with Mictype6\n");

if((data[0] & MicTypeMask) == 0)
    printf("device without Mic\n");
于 2012-08-01T07:38:33.780 回答
0

data[0] & Mictype7如果结果不为 0,即设置了 3 位中的任何一个,则将评估为 true。以下将精确匹配 MicType7: if(data[0] & Mictype7 == Mictype7)

试试这个来看看这个概念: if (Mictype7 & Mictype6) printf("Oh what is it?!!");

于 2012-08-01T07:18:19.947 回答
0

我建议你删除其他部分。因为它不必要地打印错误消息。

 readCamSpecs()
    {            
        if(!data[0])
            printf("Print your error message stating nothing is connected. \n");

        if(data[0] &  Video)
            printf("device with Video\n");

        if(data[0] & Audio) 
            printf("device with Audio\n");

        if(data[0] & Mictype7)
            printf("device with Mictype7\n");

        if(data[0] & Mictype6)
            printf("device with Mictype6\n");    
    }
于 2012-08-01T07:30:20.360 回答