[英]Understanding “Bitwise-And (&)” and “Unary complement(~)” in c++
I have some trouble understanding Bitwise-And
and Unary Complement
when both are used in this code snippet 当在这段代码中使用Bitwise-And
和Unary Complement
时,我有点麻烦
if((oldByte==m_DLE) & (newByte==m_STX)) {
int data_index=0;
//This below line --- does it returns true if both the oldByte and newByte are not true
//and within timeout
while((timeout.read_s()<m_timeout) & ~((oldByte==m_DLE) & (newByte==m_ETX))) {
if(Serial.available()>0) {
oldByte=newByte;
newByte=Serial.read();
if(newByte==m_DLE) {
.
.
.
are the both operators & ~
are performing a logical not operation like checking until if both oldByte
and newByte
are false 是两个运算符& ~
正在执行逻辑非运算,如检查,直到oldByte
和newByte
都为假
The above code is from the link --> line 227 of the code 上面的代码来自链接 - >代码的第227行
I am trying to use the implement the code for my application in C but without the timing functions 我试图在C中使用我的应用程序的代码实现,但没有计时功能
if((oldByte==DLE) && (newByte== STX)) {
data_index = 0;
// is this the correct implematation for above C++ code to C
while(! ((oldByte== DLE) && (newByte== ETX))){
oldByte = newByte;
Is this method correct for implementing in C 这种方法在C中实现是否正确
(timeout.read_s()<m_timeout) & ~((oldByte==m_DLE) & (newByte==m_ETX))
is equivalent to (but probably less readable than) 相当于(但可能不太可读)
(timeout.read_s()<m_timeout) && !(oldByte==m_DLE && newByte==m_ETX)
which is equivalent to (and IMO less readable than) 相当于(和IMO的可读性不如)
(timeout.read_s()<m_timeout) && (oldByte!=m_DLE || newByte!=m_ETX)
Edit: should add a caveat about short-circuiting. 编辑:应该添加一个关于短路的警告。 Although the particular example statements will all return the same value, using && or || 虽然特定的示例语句都将使用&&或||返回相同的值 will skip evaluating pieces that can't impact the result. 将跳过评估不会影响结果的部分。 This isn't important in your specific example, but could be very important in an example like this: 这在您的具体示例中并不重要,但在以下示例中可能非常重要:
(oldByte!=nullptr & *oldByte == m_ETX) // will crash when oldByte=nullptr.
(oldByte!=nullptr && *oldByte == m_ETX) // will evaluate to false when oldByte=nullptr.
Since the equality-operator (==) yields 0 or 1 as a result, you can use bitwise and, too. 由于等于运算符(==)产生0或1,因此您也可以使用按位运算。 (foo==1) & ~(bar==1) works too, since the AND with (foo==1), which always results in 1 and 0, masks all other bits in ~(bar==1). (foo == 1)&〜(bar == 1)也有效,因为AND与(foo == 1)总是导致1和0,掩盖了〜(bar == 1)中的所有其他位。 However, it is strongly recommended to use the logical counterparts &&, || 但是,强烈建议使用逻辑对应项&&,|| and !. 而且!
The following would not work as expected: 以下内容无法按预期工作:
if (~(bar == 1) & ~(foo == 1))
eg if foo = bar = 1, then it would evaluate to 0xfffffffe on ia32, which is different from 0 and therefore "TRUE" 例如,如果foo = bar = 1,那么它将在ia32上评估为0xfffffffe,这与0不同,因此“TRUE”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.