20120728

Multiplication of two numbers using BITWISE operators

//How will you multiply two numbers using BITWISE operators
#include<stdio.h>
main()
{
   int a,b,result;
   printf("nEnter the numbers to be multiplied :");
   scanf("%d%d",&a,&b);
   result=0;
   while(b != 0)               // Iterate the loop till b==0
   {
      if (b&01)               // Logical ANDing of the value of b with 01
      result=result+a; // Update the result with the new value of a.
      a<<=1;              // Left shifting the value contained in 'a' by 1.
      b>>=1;             // Right shifting the value contained in 'b' by 1.
   }
   printf("nResult:%d",result);
}

//program to set and show bit at nth position

#include<stdio.h>
void showBits(int);
void bitSet(int n, int b)
{
    printf("Your No:\n");
    showBits(n);

     unsigned int s=1;

     s=s<<b-1;
     n=n|s;
     printf("After setting bit at %d it becomes: %d \n",b,n);
     showBits(n);

}

void showBits(int m)
{
    unsigned int s=1;
    s=s<<sizeof(m)*8-1;
// since 1 byte=8 bits So size of int*8 ie 4*8= 32nd bit position
//ie left most position of  bit in binary representation
// Since a 64-bit machine is machine  is 8 bytes aligned
    while(s>0)
    {
    if(m&s)
        printf("1");
    else
        printf("0");
    s=s>>1;
    }
    printf("\n");
}

int main()
{
int n,b;
printf("Enter Number and bit to set:\n");
scanf("%d%d",&n,&b);
bitSet(n,b);
return 0;
}
/*
Enter a Numaber and Bit position to set:
17
3
Your Number
0000000000010001
After Setting Bit at 3rd position it becomes:21
0000000000010101
*/
Simples Way to learn Data Structure in C++ CPP or C


C++ Program for Circular Queue implementation using linked list
 
C++ program for Circular Queue implementation using Array

C++ program for reversing single Linked list nodes 

C++ Program for sorted single linked list with class

C++ Program for BST-Binary Search Tree   

Previous                             Home                               Next

2 comments:

  1. Multiplication of two numbers using BITWISE operators
    How to use bitwise operator to multiply two numbers
    Multiplication of two numbers using BITWISE operators
    How to use bitwise operator to multiply two numbers
    Multiplication of two numbers using BITWISE operators
    How to use bitwise operator to multiply two numbers

    ReplyDelete
  2. Program to multiply two numbers/digits without using multiplication and addition operator
    Program to multiply two numbers/digits without using multiplication and addition operator
    Multiplication of two numbers using BITWISE operators
    How to use bitwise operator to multiply two numbers

    ReplyDelete