2015-12-04 20 views
3

我有一些很難理解Bitwise-AndUnary Complement時,無論是在此代碼段理解「按位與(&)」和「一元補碼(〜)」在C++中

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) { 
          . 
          . 
          . 

使用是兩個運營商& ~像被檢查執行邏輯不操作,直到如果兩個oldBytenewByte是假

上面的代碼是從link - 的代碼>線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

+1

請求程序員對代碼進行模糊處理。 (幾個&看起來像一個邏輯&&) –

+1

@DieterLücking - 我試過了,但沒有迴應..有點舊的帖子在GitHub – user2345

+0

C&C++不是同一種語言。標籤(正確設置時)旨在節省時間。 –

回答

5
(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. 
2

由於平等,運算符(==)產生0或1作爲結果,您也可以使用按位。 (foo == 1)&〜(bar == 1)也起作用,因爲總是產生1和0的AND與(foo == 1)會掩蓋〜(bar == 1)中的所有其他位。不過,強烈建議使用邏輯對應部分& &,||和!

預期下是行不通的:

if (~(bar == 1) & ~(foo == 1)) 

例如如果富=巴= 1,則它會評估爲0xfffffffe IA32上,這是不同於0,並且因此 「TRUE」