Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invert bitwise shift operator / power of two

I have the following simple equation in my C# program to convert a number to a resulting value:

sectorSize = 1 << sectorShift;

Is there some sort of inverse operation that will allow me to go the other way as well?

sectorShift = ???

I know that you can implement a loop, but that's a little bit of an overkill. I've never had to do this before, so I have no idea and I can't find anything online about it. The equation I need only needs to produce valid results when sectorSize is a power of two; the rest of the domain can go to hell for all I care.

like image 620
leviathanbadger Avatar asked Mar 28 '12 20:03

leviathanbadger


2 Answers

Here are five ways to do that in C. Translating them to correct C# is left as an exercise. Be extremely careful.

http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious

Frankly, I would personally always go with the loop. It is not clear to me why you believe that simple and obviously correct code is "overkill".

like image 62
Eric Lippert Avatar answered Sep 29 '22 16:09

Eric Lippert


Logarithms. But since you don't want to do that, use a loop and/or lookup table.

like image 31
Ignacio Vazquez-Abrams Avatar answered Sep 29 '22 16:09

Ignacio Vazquez-Abrams