|
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
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-10-19 23:39
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社