tags:

views:

118

answers:

2

i need create function which returns d th bit of given number can anybody help me?

+1  A: 

This will give you a specific bit in a number:

(number >> bit) & 1

If for example number is 32 (binary 00100000) and bit is 5, you will get the value 1.

In the code >> is the shift right operator and & is the binary and operator.

Guffa
+4  A: 

To return the Nth digit of a number, do:

digit = (number / base^N) mod base

Notes

  • / is integer-division here.
  • base is 10 for decimal, 8 for octal, 16 for hexadecimal, etc. (though for bases > 10 you will need to convert the number you get to a proper digit, since you'll get 11-15 for hexadecimal for instance, but it should really be the digit A-F)

where "N" is counted from the right side, zero-based. If you need to count from the left it's probably easier if you just convert to a string and use substring instead.

For a single bit:

bit = (number >> N) and 1

where again N is counted from the right, and zero-based. Though, you can also use the first variant for bits, just use a base of 2, but it might be slightly better performance with the bit-wise operations than with division and mod.

Lasse V. Karlsen