Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get nth bit (from right) in a binary equivalent of an integer in PHP?

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

like image 466
understack Avatar asked Apr 15 '10 08:04

understack


People also ask

How do I extract a bit from an integer?

printf("int has %ud bits\n", sizeof(int) * 8); sizeof() returns the size in bytes of an integer, and then you multiply that result by 8 (bits per byte in 99.999% of cases)to get the size in bits of your integer, and therefore the size of the masks you have to apply.

What is rightmost set bit?

Then the rightmost set bit in n will be the position of the only set bit in the result. Note that if n is odd, we can directly return 1 as the first bit is always set for odd numbers. For example, the number 20 in binary is 00010100 , and the position of the rightmost set bit is 3. 00010100 & (n = 20)


1 Answers

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

($x >> 1) & 1
like image 151
Andrey Avatar answered Oct 10 '22 03:10

Andrey