当在此代码段中使用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) {
.
.
.两个操作符& ~是否都在执行逻辑上的非操作,比如检查,直到oldByte和newByte都是假的。
以上代码来自于代码的链接 ->第227行。
我试图用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;这个方法在C中实现正确吗?
发布于 2015-12-04 19:48:04
(timeout.read_s()<m_timeout) & ~((oldByte==m_DLE) & (newByte==m_ETX))相当于(但可能不如)
(timeout.read_s()<m_timeout) && !(oldByte==m_DLE && newByte==m_ETX)它相当于(而IMO的可读性低于)。
(timeout.read_s()<m_timeout) && (oldByte!=m_DLE || newByte!=m_ETX)编辑:应该添加一个关于短路的警告。虽然特定的示例语句都将返回相同的值,但使用&或\将跳过不会影响结果的计算片段。这在您的具体示例中并不重要,但在这样的示例中可能非常重要:
(oldByte!=nullptr & *oldByte == m_ETX) // will crash when oldByte=nullptr.
(oldByte!=nullptr && *oldByte == m_ETX) // will evaluate to false when oldByte=nullptr.发布于 2015-12-04 19:37:43
由于相等运算符(==)的结果是0或1,所以您也可以按位使用。(foo==1) & ~(bar==1)也能工作,因为AND (foo==1)总是导致1和0,它掩盖了~(bar==1)中的所有其他位。但是,强烈建议使用逻辑对应物&、\和!。
下列情况将不象预期的那样起作用:
if (~(bar == 1) & ~(foo == 1))例如,如果foo = bar = 1,那么它将在ia32上计算为0 0xfffffffe,这与0不同,因此"TRUE“
https://stackoverflow.com/questions/34096090
复制相似问题