返回a&b会发生什么

问题描述 投票:-3回答:2

如果我有一个返回以下内容的函数,该怎么办:

        inline bool IsInCategory(EventCategory category) {
            return GetCategoryFlags() & category;
        }

在这种情况下,“&”运算符到底在做什么?我可以在cppreference.com上找到它。

c++ ampersand
2个回答
0
投票

AND是一个二进制函数,需要2组位(相等大小),用ab遍历每一位并返回另一组位,用c表示,其中ith如果同时启用了ith和'b'中的a位,则启用该位。


0
投票

&是按位运算符,它返回两个操作数的逐位&运算,在该函数的情况下,在返回时强制转换为bool,因此,如果函数的至少一位返回true第一个操作数与第二个操作数的位匹配(顺序相同),假设两个操作数都是一个字节大小的数据(即:unsigned char)例如:

first operand is  01000100
second operand is 00100100
& returns         00000100

bool of (00000100) is true
(cast to bool for a byte is true if at least one bit is 1)

另一个例子:

first operand is  01000100
second operand is 10000010
& returns :       00000000

cast to bool of (00000000) is false
(cast to bool for a byte is false if every bit is equal to 0).
© www.soinside.com 2019 - 2024. All rights reserved.