views:

125

answers:

2

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

+5  A: 

http://php.net/manual/en/language.operators.bitwise.php

($x >> 1) & 1
Andrey
And function to get nth bit:function nbit($number, $n) { return ($number >> $n-1) }
Tomasz Struczyński
stereofrog
@stereofrog: you're right, but for nth bit, you've to find out pow(2, n-1) which is again done by shifting.
understack
+1  A: 

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)
deceze
holy sh.. that's even more difficult to read then bit shifts. However very original way of doing this.
Pim Jager
@Pim Lol, thanks. Logically it's pretty straight forward though, maybe too much so. ;)
deceze