0

Say I assign the following fruits:

array ('1' => 'apple', '2' => 'banana', '4' => 'grape', '8' => 'orange')

If I wanted to represent apple and banana, I could just do the following: 0001 OR 0010 to get 0011 (or 3), right?

Given the number 3, how do I convert that to 1 and 2?

4
  • 4
    0001 AND 0010 is 0. Probably you mean 0001 OR 0010 Commented Jul 1, 2011 at 1:36
  • No, neither. He should be using the bit-wise & and | if anything. Commented Jul 1, 2011 at 1:37
  • 1
    FYI, it's easier to produce proper bit masks with the bitwise shift left operator: 2 << 3; // 8 Commented Jul 1, 2011 at 1:41
  • 2
    @Jonah In order to produce powers of 2, it is a lot easier to use bitshift instead of power. Commented Jul 1, 2011 at 1:42

3 Answers 3

3

All keys will be loaded into $keys:

$keys = array();
$value = 3;

foreach ($arr as $key => $val)
{
   if ($value & $key)
   {
      $keys[] = $key;
   }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Generally you use bitmasks this way (language is irrelevant)

BANANA = 0x1
APPLE = 0x2
GRAPE = 0x4
LEMON = 0x8
PAPAYA = 0x10
GUAYABA = 0x20


myFavoriteFruits = BANANA | GRAPE // I like both bananas and grapes.

Now to test if I like Bananas you evalute:

myFavoriteFruits & BANANA

Comments

1

use the bitwise AND (&) operator in a loop to test the bits.

1 Comment

looks like Tim Cooper provided one :^)

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.