use*_*345 3 c c++ bitwise-operators logical-operators
我有一些麻烦的了解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) {
.
.
.
Run Code Online (Sandbox Code Playgroud)
被两个运营商& ~都像检查,直到执行逻辑操作不如果两个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;
Run Code Online (Sandbox Code Playgroud)
这种方法在C中实现是否正确
(timeout.read_s()<m_timeout) & ~((oldByte==m_DLE) & (newByte==m_ETX))
Run Code Online (Sandbox Code Playgroud)
相当于(但可能不太可读)
(timeout.read_s()<m_timeout) && !(oldByte==m_DLE && newByte==m_ETX)
Run Code Online (Sandbox Code Playgroud)
相当于(和IMO的可读性不如)
(timeout.read_s()<m_timeout) && (oldByte!=m_DLE || newByte!=m_ETX)
Run Code Online (Sandbox Code Playgroud)
编辑:应该添加一个关于短路的警告.虽然特定的示例语句都将使用&&或||返回相同的值 将跳过评估不会影响结果的部分.这在您的具体示例中并不重要,但在以下示例中可能非常重要:
(oldByte!=nullptr & *oldByte == m_ETX) // will crash when oldByte=nullptr.
(oldByte!=nullptr && *oldByte == m_ETX) // will evaluate to false when oldByte=nullptr.
Run Code Online (Sandbox Code Playgroud)