How to get nth bit (from right) in a binary equivalent of an integer in PHP?
Suppose I want to find 开发者_如何学Python2nd bit in binary equivalent of 13 (binary : 1101). It should return 0.
http://php.net/manual/en/language.operators.bitwise.php
($x >> 1) & 1
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)
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:
extract_bits(13,1,2);
精彩评论