Tutorial :Decimal to Bit (Binary)



Question:

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


Solution:1

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


Solution:2

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


Solution:3

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


Solution:4

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  


Solution:5

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »