Decimal to Bit (Binary)

Tag: algorithm Author: zhao543483379 Date: 2009-07-13

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

"bit more complicated"...pun intended?

Best Answer

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) )

comments:

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

Other Answer1

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...

comments:

+1. nice, quick answer!

Other Answer2

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

comments:

i.e. exactly like @Mark Rushakoff's answer !!

Other Answer3

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

comments:

It is a ton of time, at that, comparing python -m timeit -n 1000 "for n in xrange(1,10000): n & (1 << (12))" with python -m timeit -n 1000 "for n in xrange(1,10000): n & (1 << (12-1))"

Other Answer4

bool IsBitTrue(int num , int pos)
{
 return ((num>>pos-1)%2==1)
}