Sem 5‎ > ‎DCCN LAB‎ > ‎

01 Understanding Bit-wise Operators

posted Nov 5, 2012, 11:49 PM by Neil Mathew   [ updated Nov 6, 2012, 6:11 AM ]

First of all, we need to understand how the bitwise operator works.



Bitwise operators are kind of advanced - they work on the binary bits of numbers. 

First, you have bitwise AND(&).
 This compares each bit. 
If the bits from both of the numbers are 1, then the resulting bit is 1. 
Otherwise, the resulting bit is 0. 

For example:

 56 00111000 
235 11101011
&------------- 
 40 00101000


Next, you have bitwise OR(|)
If either bit is 1, then the resulting bit is 1.

 56 00111000
235 11101011 
|-------------
251 11111011 


Also, you have bitwise XOR(^)
If only one of the bits is 1, then the resulting bit is 1 
(if both are 1, or neither are 1, then the resulting bit is 0).

 56 00111000
235 11101011
^---------------
211 11010011


The final bitwise operator is bitwise NOT (~). 
This works on only one operand - it simply flips the bits.

 56 00111000
~-------------
199 11000111



Second, we need to know HOW they can be used.

One main function is the easy conversion of decimal values to binary and vice versa. 

We can use two operations to perform a number conversion.
1. Bit-wise AND operation. To compare the bits one by one.
2. Bit-wise Right - Shift Operation. To divide the number by 2.

Depending on the no of bits in the system, we need an initial constant.

For 4-bit numbers, we use 8 (1000)

Each step, we divide this constant by 2 using bit-wise right shift operator >>.
8>>1 = 4
4>>1 = 2
2>>1 = 1

( Operandtoshift >> NoOfTimesDone )

step-1
======

1 1 0 0 = 12
1 0 0 0 = 08
&-----------

1 0 0 0 (12 & 8)

Not Zero. Print 1.




1
 step-2
======
1 1 0 0 = 12
0 1 0 0 = 04
&-----------

0 1 0 0 
(12 & 4)

Not Zero. Print 1.




1
 
 step-3
======
1 1 0 0 = 12
0 0 1 0 = 02
&-----------

0 0 0 0 
(12 & 2)

Zero. Print 0.




0 
step-4
======
1 1 0 0 = 12
0 0 0 1 = 01 
&-----------

0 0 0 0 (12 & 1)

Zero. Print 0.

 


0


So, Binary equivalent of 12 = 1100

Comments