Using shift operator for faster division and multiplication

Discussion in 'Programming' started by pradeep, Feb 21, 2007.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    Multiplications

    12 * 2 = 12 << 1
    12 * 4 = 12 << 2
    12 * 8 = 12 << 3
    12 * 16 = 12 << 4
    12 * 32 = 12 << 5
    12 * 64 = 12 << 6
    12 * 128 = 12 << 7
    12 * 256 = 12 << 8

    Divisions

    12 / 2 = 12 >> 1
    12 / 4 = 12 >> 2
    12 / 8 = 12 >> 3
    12 / 16 = 12 >> 4
    12 / 32 = 12 >> 5
    12 / 64 = 12 >> 6
    12 / 128 = 12 >> 7
    12 / 256 = 12 >> 8


    Code:
     #include<stdio.h>
     
     void main(void)
     {
       int a;
     
       a = 12 << 1;
     
       printf("%d",a);
     }
     
     
  2. mayjune

    mayjune New Member

    Joined:
    Jun 14, 2009
    Messages:
    814
    Likes Received:
    33
    Trophy Points:
    0
    Occupation:
    Student
    Location:
    Pune,Delhi
    in machine terms,
    for i12 / 256, 12 >> 8 is faster. Is that what you mean?
    or just for easier calculations?
     
  3. teacher

    teacher New Member

    Joined:
    Mar 27, 2011
    Messages:
    66
    Likes Received:
    8
    Trophy Points:
    0
    Occupation:
    i hate jobs
    Location:
    india,agra
    Home Page:
    http://www.crazylearner.in
    this method does not work if you have logic one at msb
    for eg
    Code:
    // before: binary equivalent 10000000 
    uint_8 t = 128;
    t<<1;
    // after: decimal equivalent : 0
    // after: binary equivalent 00000000 
    
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice