说我有以下代码:
class Restaurant
{
const FRUITS = 1;
const VEGETABLES = 2;
const MEET = 4;
static public $data = [
self::FRUITS => ['apple', 'banana'],
self::VEGETABLES => ['tomato', 'potato'],
self::MEET => ['beef', 'pig']
];
public static function getSomething($byte)
{
// unknown logic for me
}
}
Restaurant::getSomething(Restaurant::FRUITS | Restaurant::MEET);
// ['apple', 'banana', 'beef', 'pig']
我需要实现一些基于按位运算的连接操作的逻辑。
最好的方法是什么?
答案 0 :(得分:4)
使用($byte & $bw) === $bw
,其中$byte
是您正在测试的任何值(例如3
),$bw
是您的按位值(例如1
,2
或4
)检查按位值是否匹配。
为什么会有效?
这很简单。当我们AND项目时,我们只使用两个值中存在的位值
$byte = 3 = 0011
$bw = 2 = 0010
AND'ed = 2 = 0010 (the same as $bw - $bw is included!)
^ 1 & 1 = 1
-----------------
$byte = 5 = 0101
$bw = 2 = 0010
AND'ed = 0 = 0000 (empty as the values do not match - $bw is NOT included)
^ 0 & 1 = 0
<强>代码:强>
<?php
class Restaurant
{
const FRUITS = 1; // 0001
const VEGETABLES = 2; // 0010
const MEET = 4; // 0100
static public $data = [
self::FRUITS => ['apple', 'banana'],
self::VEGETABLES => ['tomato', 'potato'],
self::MEET => ['beef', 'pig']
];
public static function getSomething($byte)
{
// Start with an empty array
$returnItems = array();
// Loop through our bitwise values
foreach (self::$data as $bw => $items) {
// Is it included in $byte?
if (($byte & $bw) === $bw) {
// Then add the items in $items to $returnItems
$returnItems = array_merge($returnItems, $items);
}
}
// Return the items
return $returnItems;
}
}
<强>测试强>:
$result = Restaurant::getSomething(Restaurant::FRUITS | Restaurant::MEET); // 5 - 0101
var_dump($result);
/*
array(4) {
[0]=>
string(5) "apple"
[1]=>
string(6) "banana"
[2]=>
string(4) "beef"
[3]=>
string(3) "pig"
}
*/
答案 1 :(得分:1)
没什么好看的我会说......
public static function getSomething($bitmask)
{
$result = [];
foreach(self::$data as $key => $value)
{
if(($key & $bitmask) !== 0)
{
$result = array_merge($result, $value);
}
}
return $result;
}