用十六进制值设置位并进行验证 (C语言)

3
在一个字节中,我设置了一些位 | 视频 | 音频 | 扬声器 | 麦克风 | 耳机 | LED 使用位来表示 | 1 | 1 | 1 | 3 | 1 | 1
除了麦克风需要 3 个字节以外,其他全部使用 1 个字节,因此可以有 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);

//设置麦克风类型为6

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)设置时会出错, 并且显示选项中的第一个。 我做错了什么?

1
给作者点个赞吧 - 他太低调了,无法为有用的回答点赞。 - Roman Saveljev
4个回答

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

2

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

请尝试使用if ( data[0] & Mictype7 == MicType7 )


运行得非常好。只需要加上额外的括号,否则它将从左到右开始比较。这对我的编译器有效,如果 ( (data[0] & Mictype7) == MicType7 )。顺便说一句,这是一个多么棒的论坛。感谢大家。很抱歉不能为你点赞,没有足够的guineas。 - user1566277

0

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

 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");    
    }

0

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

尝试一下以了解概念: if (Mictype7 & Mictype6) printf("Oh what is it?!!");


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接