首页 > 解决方案 > 在 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,...)

标签: algorithmvalidationlaravel-5

解决方案


根据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);
            },
        ]
    ];
}

推荐阅读