我有一个已知值的列表:
const VAL1 = 1
const VAL2 = 2
const VAL3 = 3
const VAL4 = 4
const VAL5 = 5
const VAL6 = 6
我提供的数字是添加了1个或更多左移值。例如,我提供了这个号码:
98
如何确定我的已知列表中的哪些值代表98?在该示例中,值将是2(VAL2),5(VAL5)和6(VAL6)(因为1 <&lt; 2 + 1&lt;&lt; 5&lt;&lt;&lt;&lt;&lt;&lt;&lt; 6 = 98)
答案 0 :(得分:0)
我终于能够通过编写以下函数来解决这个问题了。这是一个更大的类的一部分,所以这只是一个片段。
const DESTINATION_ID_USAGE_VALS = [
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,
21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,
39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,
57,58,59,60,61,62,
];
public static function getDestinationIdUsageSetValues($computedMask)
{
$current_total = $computedMask;
$values = [];
foreach(array_reverse(self::DESTINATION_ID_USAGE_VALS) as $possible_value) {
$check = (1 << $possible_value);
if($current_total == $check) {
$values[] = $possible_value;
$current_total = $current_total - $check;
}
elseif($check < $current_total) {
$values[] = $possible_value;
$current_total = $current_total - $check;
}
}
return $values;
}
实施例:
$vals = getDestinationIdUsageSetValues(4194368);
结果(数组):6,22