Question

I want to fetch different values from one number by masking.I have explained it follow.

I have one number "1540104" and want to get related binary values and their related decimal values from it .

1540104

101111000000000001000

100000000000000000000 => 1048576

001000000000000000000 => 262144

000100000000000000000 => 131072

000010000000000000000 => 65536

000001000000000000000 => 32768

000000000000000001000 => 8

So how to set logic to get this related decimal values.

Was it helpful?

Solution 2

I liked better josh bobruk's answer above (thus upvoted), but here's mine anyway:

for ($i=1; $i<=1540104;$i=$i*2) {
    $res = $i & 1540104;
    if ($res) {
        echo "$i: $res<br/>";
    }

}

OTHER TIPS

This will loop over your input and echo out all the decimal values of the bits that are set:

$input = 1540104;
$bit = 0;

while ($input > 0) {
  if ($input & 0x1) {
    echo pow(2, $bit);
    echo "<br/>";
  }
  $bit++;
  $input = $input >> 1;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top