12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- <?php
- namespace loyalsoft;
- /**
- * bit操作类
- * @author Administrator
- */
- class Bits {
- //put your code here
- /**
- * 获取一个int(32)值的bit数组
- * @param int $intVal
- * @return array
- */
- public static function GetBits(int $intVal): array {
- $arr = [];
- $x = 0;
- for ($i = 0; $i <= 31; $i++) {
- $x = 1 << $i;
- $arr[$i] = (($intVal & $x) == $x);
- }
- return $arr;
- }
- /**
- * 返回Int数据中某一位是否为1
- * @param int $value 待分析的int值
- * @param int $index 32位数据的从右向左的偏移位索引(0~31)
- * @return bool true表示该位为1,false表示该位为0
- */
- public static function GetBitValue(int $value, int $index): bool {
- my_Assert($index >= 0 && $index <= 31, "index is Out Of Range(0..31)."); //索引出错
- $val = 1 << $index;
- return ($value & $val) == $val;
- }
- /**
- * 设定Int数据中某一位的值
- * @param int $value 需要修改的int值
- * @param int $index 32位数据的从右向左的偏移位移索引(0~31)
- * @param bool $newBitValue true设该位为1, false设为0.
- * @return int 返回修改后的值
- */
- public static function SetBitValue(int &$value, int $index, bool $newBitValue): int {
- my_Assert($index >= 0 && $index <= 31, "index is Out Of Range(0..31)."); //索引出错
- $val = 1 << $index;
- $value = $newBitValue ? ($value | $val) : ($value & ~$val);
- return $value;
- }
- }
|