Suppose I want to find 2nd bit in binary equivalent of 13 (binary : 1101). It should return 0.
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.
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)
http://php.net/manual/en/language.operators.bitwise.php
($x >> 1) & 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With