加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

理解c中的“按位 – 和(&)”和“一元补码(?)”

发布时间:2020-12-16 10:00:28 所属栏目:百科 来源:网络整理
导读:当在这段代码中使用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((time
当在这段代码中使用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都为false

以上代码来自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中实现是否正确

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读