简体   繁体   English

按位操作位检查

[英]Bitwise operation bit check

Is this correct way to check if bits are set in some variable and store them in another variable? 这是检查位是否在某个变量中设置并将其存储在另一个变量中的正确方法吗? Just ignore variable names, image[] and mask variables are 1 byte and first_hline_first_row and second_hline_first_row are 2 byte. 只需忽略变量名,image []和mask变量为1字节,first_hline_first_row和second_hline_first_row为2字节。

 for(i=0; i<16; i++){

    if(image[i] & mask1)         first_hline_first_row    |=   (1<<i);
    else                         first_hline_first_row    &=~  (0<<i);

    if(image[i] & mask2)         second_hline_first_row   |=   (1<<i);
    else                         second_hline_first_row   &=~  (0<<i);
    }   

Two things: 两件事情:

  • image[i] & mask1 only checks whether image[i] and mask1 have at least one bit in common. image[i] & mask1仅检查image[i]mask1是否具有至少一位相同。 Is this your intention? 这是你的意图吗?
  • first_hline_first_row &=~ (0<<i); does nothing ( ~(0<<i) is all ones). 什么都不做( ~(0<<i)都是1)。

From the comments I'm guessing that this is what you meant to write: 从评论中,我猜测这就是您要写的内容:

for(i=0; i<16; i++){
     if(image[i] & mask1)
     {
         first_hline_first_row    |=   (1<<i);
     }
     else                         
     {
         first_hline_first_row    &=~  (1<<i);
     }

     if(image[i] & mask2)
     {
         second_hline_first_row   |=   (1<<i);
     }
     else
     {
         second_hline_first_row   &=~  (1<<i);
     } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM