tags:

views:

307

answers:

5

It's easy to convert Decimal to Binary and vice-versa in any language, but I need a function that's a bit more complicated.

Given a decimal number and a binary place, I need to know if the binary bit is On or Off (True or False).

Example:

IsBitTrue(30,1) // output is False since 30 = 11110
IsBitTrue(30,2) // output is True
IsBitTrue(30,3) // output is True

The function will be called a LOT of times per second, so a fast algorithm is necessary.. Your help is very much appreciated :D

+6  A: 

Print this page out, hang above your monitor

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

But it's roughly something like

if ( value & (1 << bit_number) )

Martin Beckett
or bitnumber-1 depending on how you are counting them
Martin Beckett
I think you mean 1 instead of 2, or `**` instead of `<<`.
Greg Hewgill
Yes, I realised just as I hit enter but then it wouldn't let me edit it for a couple of minutes
Martin Beckett
Chosen as correct answer because of the really handy link :D
GaiusSensei
+4  A: 

Really?

def IsBitTrue(num, bit):
    return (num & (1 << (bit-1))) > 0

Normally, it would be 1<<bit, but since you wanted to index the LSB as 1...

Mark Rushakoff
+1. nice, quick answer!
Mitch Wheat
A: 

Use your 'easy' function to convert the decimal number to binary, and then compare with a bit mask representing the bit you are testing.

Mitch Wheat
i.e. exactly like @Mark Rushakoff's answer !!
Mitch Wheat
A: 

Python

def isBitTrue( number, position ):
    mask = 1 << (position-1)
    return bool( number & mask )

If you number the positions from 0 (instead of 1), you can save a ton of time.

>>> isBitTrue(30,1)
False
>>> isBitTrue(30,2)
True
>>> isBitTrue(30,3)
True
S.Lott
Steve Jessop
A: 
bool IsBitTrue(int num , int pos)
{
 return ((num>>pos-1)%2==1)
}
Jobi Joy