algorithm - 在 Laravel 中自定义验证函数
问题描述
我很好奇($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 Hacks和PHP 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);
},
]
];
}
推荐阅读
- flutter - 在 Flutter 中,如何使用 .where 来检查字段是否在本地列表中?
- android - 使用 wowza 引擎进行实时流的 AR 面部过滤器
- python - 如何用硒选择一个[不断变化的]元素
- java - 在 ARcore 移动应用程序中显示 .png 或 .jpeg 图像?
- ios - Xcode 和 Swift UI 中是否存在导致不相关错误的已知错误?
- amazon-web-services - 调试 AWS HTTP API (beta) JWT Authorizer
- ios - 如何在包装器 Swift View 中使用自定义 UIView 的扩展功能?
- javascript - 自定义滚动条跨浏览器支持
- python - One-Hot-Encode only integers, slices(`:`), ellipsis(`...`), numpy.newaxis(`None`) and integer or boolean arrays are valid indicies problem
- amazon-web-services - 列出所有私有 IP,除了来自 awscli 的少数标签名称