Search Unity

How do I do those bit shifts operations now again?

Discussion in 'Scripting' started by recon, Nov 23, 2011.

  1. recon

    recon

    Joined:
    Nov 28, 2009
    Posts:
    119
    In my code I have an excessive amounts of a / b (both integers) calculations where b is always a power of two number, so my question is if I could replace the division by a bit shift operation?
    It's been a while since I had to do something like this so it would be very nice if someone could refresh my memory on the subject.

    Thanks!
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,225
    Code (csharp):
    1. var foo = 8;
    2. foo >>= 1;  // foo = 4
    --Eric
     
  3. recon

    recon

    Joined:
    Nov 28, 2009
    Posts:
    119
    Okey, so that's for division by 2, does the same code work if I wanted division by 4, 8, 16, 32 etc.?
     
  4. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,225
    >> 2

    >> 3

    >> 4

    >> 5

    I hope you've gotten the idea by now. ;)

    --Eric
     
  5. recon

    recon

    Joined:
    Nov 28, 2009
    Posts:
    119
    Haha, yes thank you for the explanation :)
     
unityunity