gpt4 book ai didi

php - 位掩码到数组

转载 作者:行者123 更新时间:2023-12-03 18:50:06 25 4
gpt4 key购买 nike

我需要从位掩码获取所有工作日。是否有分解位掩码的功能?
例如:

const MONDAY    = 1 << 0; // 1
const TUESSAY = 1 << 1; // 2
const WEDNESDAY = 1 << 2; // 4
const THURSSAY = 1 << 3; // 8
const FRIDAY = 1 << 4; // 16
const SATURDAY = 1 << 5; // 32
const SUNDAY = 1 << 6; // 64

function bitmaskToArray(int $bitmask): array
{
//...
}

$wednesdayAndMonday = WEDNESDAY | MONDAY;

var_dump(bitmaskToArray($wednesdayAndMonday));
我看到了一种解决方案,但我相信它不是最好的:
const WEEKDAYS = [
MONDAY,
TUESSAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY,
];

function bitmaskToArray(int $bitmask): array
{
$result = [];
foreach (WEEKDAYS as $weekday) {
if ($bitmask & $weekday) {
$result []= $weekday;
}
}

return $result;
}

最佳答案

您可以遍历位数并计算循环中的位移。

function bitmaskToArray(int $bitmask, int $maxbits): array
{
$result = [];
for ($thisbit = 1; $i < (1 < $maxbits); $thisbit <<= 1) {
if ($bitmask & $thisbit) {
$result[] = $thisbit;
}
}

return $result;
}
然后您可以调用 bitmaskToArray($wednesdayAndMonday, count(WEEKDAYS))

关于php - 位掩码到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67129324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com