Search This Blog

Tuesday, December 27, 2011

Logic operations in 8051 C

Everyone must be familiar with AND(&&), OR(||) and NOT(!) operators in C. well there are also bitwise logical operators also known as AND(&), OR(|), EX-OR(^), Inverter(~), shift right(>>) and shift left(<<).
These bit wise operators are widely used in embedded systems and control.

Bit wise logic operators for C
A
B
A & B
A | B
A ^ B
Y = ~B
0
0
0
0
0
1
0
1
0
1
1
0
1
0
0
1
1

1
1
1
1
0


Used as:
ANDing
0x35 & 0x45 = 0x05
ORing
0x35 | 0x45 = 0x75
XORing
0x35 ^ 0x45 = 0x70
INVERTing
~0x35 = 0xCA

Usage of bit wise shift operation:
Data>>number of bits to be shifted right
Data<<number of bits to be shifted left
0x50>>4 = 0x05
0x45<<2 = 0xB4

An example of logic operation can be seen below.

#include<reg51.h>
/*
 * issue ascii char to P2 as follows
 * P3.1                   P3.0
 * 0                         0              send 0
 * 0                         1              send 1
 * 1                         0              send 2
 * 1                         1              send 3
 *
 */
void main()
{
                unsigned char z;
                z = P1;   //read P1
                z = z & 0x03;
                // mask the unused bits
                switch(z)
                {
                                case(0): P2 = '0';
                                                 break;
                                case(1): P2 = '1';
                                                 break;
                                case(2): P2 = '2';
                                                 break;
                                case(3): P2 = '3';
                                                 break;

                }// end of switch
}// end of main
// end of program

No comments:

Post a Comment