we can also use the logical operators to


  We can also use the logical operators to numbers directly and  perform simple bit manipulation . The operators are

    &  Bitwise AND
    |  Bitwise OR
    ^  Bitwise exclusive or 
    ~  Bitwise one's complement i.e. NOT
    <<  Left shift
    >>   Right shift

Example
  A 8 bit number represents a coded function, bit  3-4 describes the operation to be performed on the number in bits 0- 2 and 5-7  the function i.e. 
 
    00    Add
    01    Subtract
    10     Divide
    11    Multiply
 
  Write a Program to extract the number and operation

Answer
We need to extract the bits 3-4, the answer is bit operators 
 
    Assume number is in the variable A i.e.  11011011
 
    Mask off the first number i.e. bit 0-2
    num1 = a & 0x07;        11011011 and
                00000111
                00000011
    
    Mask off the second number i.e. bit 5 -7
    num2 = a & 0xe0;        11011011 and
                11100000
                11000000
 
    We need to shift num2 down by 5 places i.e.
    num2 = num2 >>5;
                00000110

This could be done in one instruction i.e.
    num2 = (a & 0xe0) >> 5;
 
  Mask off the operation bits i.e. bit 4-5
    operation = (a & 0x18) >> 3;
 
  We can then use the switch statement to select each operation
  switch(operation)
  {
  case 0:  
    total = num1+num2;
    break;
  case 1: 
     total = num1-num2;
    break;
  case 2:  
    total = num1/num2;
    break;
  case 3:  
    total = num1*num2;
    break;
  }
Hence the entire program is 
  #include
  void main()
  { 
  char prompt;
  /*Author : Mr James Mc Carren 
  Company: Staffordshire University 
   Date: 26th August 2012 
  Version 1.0 
   Function : To show bit manipulation
   Modifications:   none*/
  int num1,num2,operation,total,a;
  printf("Please enter in the number\n\r");
  scanf("%x",&a);
  num1 = a & 0x07;  
  num2 = (a & 0xe0) >> 5 ;
  operation = (a & 0x18) >> 3;
  switch(operation)
  {
  case 0:   total = num1+num2;
    break;
  case 1:  total = num1-num2;
    break;
  case 2:  total = num1/num2;
    break;
  case 3:  total = num1*num2;
    break;
  }
  printf("The total is %d\n\r",total); 
  printf("Press and key to exit \n\r");
  scanf("\n%c",&prompt);
  }

Request for Solution File

Ask an Expert for Answer!!
Computer Engineering: we can also use the logical operators to
Reference No:- TGS0265225

Expected delivery within 24 Hours