gpt4 book ai didi

algorithm - 在 Laravel 中自定义验证函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:07:34 24 4
gpt4 key购买 nike

我很好奇 ($value & ($value - 1)) != 0 它是如何在下面的验证中知道数字是 2 的幂的?!

function ($attribute, $value, $fail) {
if ($value == 0 || ($value & ($value - 1)) != 0) {
$fail($attribute . ' is not power of 2!');
}
}

除了2的幂数之外,如果我还想得到2的幂数之间的数,该怎么办?我可以使用和修改这个命令吗?(例如数字:1,2,3,4,6,8,12,16,...)

最佳答案

根据 Bit Twiddling HacksPHP Bitwise Operators

public function rules()
{
return [
'threshold' => [
'required',
'between:1,1000',
function ($attribute, $value, $fail) {
$err_message = "Given Value is not acceptable";
$next_power_of_2 = $value-1;
$next_power_of_2 |= $next_power_of_2 >> 1;
$next_power_of_2 |= $next_power_of_2 >> 2;
$next_power_of_2 |= $next_power_of_2 >> 4;
$next_power_of_2 |= $next_power_of_2 >> 8;
$next_power_of_2 |= $next_power_of_2 >> 16;
//closest upper power 2 to given number
$next_power_of_2++;
//closes lower power 2 number to given value
$previous_power_of_2 = $next_power_of_2 >> 1;

if ($value == 0) $fail($err_message);//check number is zero

else if (($value & ($value - 1)) == 0) {}//check number is power of 2

else if (($next_power_of_2 + $previous_power_of_2) / 2 != $value) //check number is between two power of 2
$fail($err_message);
},
]
];
}

关于algorithm - 在 Laravel 中自定义验证函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54743262/

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