Take the 2-minute tour ×

Suppose I want to find 2nd bit in binary equivalent of 13 (binary : 1101). It should return 0.

share|improve this question
add comment

3 Answers

up vote 12 down vote accepted


($x >> 1) & 1
share|improve this answer
And function to get nth bit: function nbit($number, $n) { return ($number >> $n-1) & 1;} –  Tomasz Struczyński Apr 15 '10 at 8:32
@stereofrog: you're right, but for nth bit, you've to find out pow(2, n-1) which is again done by shifting. –  understack Apr 17 '10 at 10:43
add comment

Here is a bit more universal function to extract also bit ranges.

function extract_bits($value, $start_pos, $end_pos)
    $mask = (1 << ($end_pos - $start_pos)) - 1;
    return ($value >> $start_pos) & $mask;

for example to extract value of the second bit from 13 it'd be:

share|improve this answer
add comment

Nice answer by Andrey, definitely go with his solution. Here's another way to do it though, using string manipulation (I know, I know...):

substr(decbin($x), -2, 1)
share|improve this answer
holy sh.. that's even more difficult to read then bit shifts. However very original way of doing this. –  Pim Jager Apr 15 '10 at 8:38
@Pim Lol, thanks. Logically it's pretty straight forward though, maybe too much so. ;) –  deceze Apr 15 '10 at 8:41
add comment

Your Answer


