0

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.

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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/>";
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.