jingweimo的个人博客分享 http://blog.sciencenet.cn/u/jingweimo

博文

Bitwise operations: a case study

已有 1407 次阅读 2018-2-28 00:47 |系统分类:科研笔记

Bitwise operators are those strange looking operators that may look hard to understand... but not any more!

Example:

unsigned char dataIn[8] = {0,0,1,0,1,0,0,1};
//unsigned int status = 0;

unsigned char status = 0;

int main()
{
   for (int i=0; i<4; i++)
   {
       if(dataIn[i]==1)
       {
           status = status | (0x01<<(7-i));
       }
       else
       {
           status = status & ~(0x01<<(7-i));
       }
   }

   return 0;
}

Explanations

1. the codes in the 'if {}' block

1). 0x01<<(7-i): shift the bits by i from the most significant position (from the right)

E.g., 0x01<<(7-1)  = 01000000.

2). status = status | (0x01<<(7-i)): set the bit in the corresponding position of dataIn

Eg., for i = 2, status = 00100000.

2. the code in the 'else{}' block

1). ~(0x01<<(7-i)): clear the bit in the poisition i from the most significant bit

E.g., ~(0x01<<(7-2)) = 11011111

2). status = status & ~(0x01<<(7-i)): clear the bit in the corresponding position of dataIn

E.g., for i=3, status =00100000

3. Output

The sequence of dataIn is masked into bits of status from the most four signficant bits. When dataIn[i] = 1, the corresponding bit is set, otherwise cleared. So, status = 00100000 (In practice, there is no effect with or without using the 'else{} block', since status is zeroed out before entering the loop).


Sources:

http://www.learncpp.com/cpp-tutorial/38-bitwise-operators/

https://code.tutsplus.com/articles/understanding-bitwise-operators--active-11301  



https://blog.sciencenet.cn/blog-578676-1101526.html

上一篇:Conversion between QImage and CV Images
下一篇:Motion Control with LabView
收藏 IP: 35.10.57.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-3-28 18:59

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部