[英]What does the following mean with respect to, bitwise operations in C?
A book on C programming states,一本关于 C 编程状态的书,
enum corvid { magpie , raven , jay , chough , corvid_num , };
# define FLOCK_MAGPIE 1 U
# define FLOCK_RAVEN 2 U
# define FLOCK_JAY 4 U
# define FLOCK_CHOUGH 8 U
# define FLOCK_EMPTY 0 U
# define FLOCK_FULL 15 U
int main ( void ) {
unsigned flock = FLOCK_EMPTY ;
if ( something ) flock |= FLOCK_JAY ;
...
if ( flock & FLOCK_CHOUGH )
do_something_chough_specific ( flock ) ;
Here the constants for each type of corvid are a power of two, and so they have exactly one bit set in their binary representation.
在这里,每种类型的 corvid 的常数都是 2 的幂,因此它们的二进制表示中只有一个位。 Membership in a flock can then be handled through the operators: |= adds a corvid to flock, and & with one of the constants tests whether a particular corvid is present
然后可以通过运算符处理群中的成员资格: |= 向群中添加一个 corvid,并且 & 使用其中一个常量测试是否存在特定的 corvid
Question.问题。 "if ( something ) flock |= FLOCK_JAY; " adds a corvid to flock but why not use assignment operator for that or "flock = FLOCK_JAY".
“if (something)flock |= FLOCK_JAY;”为flock 添加了一个corvid,但为什么不使用赋值运算符或“flock = FLOCK_JAY”。
Also, is "if ( flock & FLOCK_CHOUGH )" gonna yield a bool type value?另外,“if (flock & FLOCK_CHOUGH)”会产生一个布尔类型的值吗?
Question.
问题。 "if ( something ) flock |= FLOCK_JAY; " adds a corvid to flock but why not use assignment operator for that or "flock = FLOCK_JAY".
“if (something)flock |= FLOCK_JAY;”为flock 添加了一个corvid,但为什么不使用赋值运算符或“flock = FLOCK_JAY”。
|=
is used whenever one wants to preserve the other bits already set inside the variable. |=
每当想要保留已在变量中设置的其他位时使用。 In this specific case it doesn't matter if =
or |=
is set since flock
has the value zero.在这种特定情况下,设置
=
或|=
无关紧要,因为flock
的值为零。
Also, is "if ( flock & FLOCK_CHOUGH )" gonna yield a bool type value?
另外,“if (flock & FLOCK_CHOUGH)”会产生一个布尔类型的值吗?
It will yield an unsigned int
since both operands are of that type.它将产生一个
unsigned int
,因为两个操作数都是那种类型。 It will hold a value which is either zero or non-zero.它将保存一个零或非零值。 This can be regarded as equivalent to a boolean condition though.
这可以被视为等效于 boolean 条件。 It will only get bool type if you explicitly do
bool b = flock & FLOCK_CHOUGH;
如果您明确执行
bool b = flock & FLOCK_CHOUGH;
则只会获得 bool 类型. .
Q1: Assigning instead of ORing would knock out other bird types. Q1:分配而不是 ORing 会淘汰其他鸟类类型。 Say
说
flock = FLOCK_MAGPIE;
If you set如果你设置
flock = FLOCK_JAY;
there would be no magipies in the flock but if you羊群中不会有喜鹊,但如果你
flock |= FLOCK_JAY;
the flock would contain both jays and magpies.羊群将包含松鸦和喜鹊。
Q2: The condition in the if statement doesn't yield a bool. Q2:if 语句中的条件不会产生布尔值。 Any non-zero value is true.
任何非零值都为真。 A zero value is false.
零值是假的。 If you want a boolean value, try
如果您想要 boolean 值,请尝试
if ((flock & FLOCK_CHOUGH) != 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.