Bits.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace loyalsoft;
  3. /**
  4. * bit操作类
  5. * @author Administrator
  6. */
  7. class Bits {
  8. //put your code here
  9. /**
  10. * 获取一个int(32)值的bit数组
  11. * @param int $intVal
  12. * @return array
  13. */
  14. public static function GetBits(int $intVal): array {
  15. $arr = [];
  16. $x = 0;
  17. for ($i = 0; $i <= 31; $i++) {
  18. $x = 1 << $i;
  19. $arr[$i] = (($intVal & $x) == $x);
  20. }
  21. return $arr;
  22. }
  23. /**
  24. * 返回Int数据中某一位是否为1
  25. * @param int $value 待分析的int值
  26. * @param int $index 32位数据的从右向左的偏移位索引(0~31)
  27. * @return bool true表示该位为1,false表示该位为0
  28. */
  29. public static function GetBitValue(int $value, int $index): bool {
  30. my_Assert($index >= 0 && $index <= 31, "index is Out Of Range(0..31)."); //索引出错
  31. $val = 1 << $index;
  32. return ($value & $val) == $val;
  33. }
  34. /**
  35. * 设定Int数据中某一位的值
  36. * @param int $value 需要修改的int值
  37. * @param int $index 32位数据的从右向左的偏移位移索引(0~31)
  38. * @param bool $newBitValue true设该位为1, false设为0.
  39. * @return int 返回修改后的值
  40. */
  41. public static function SetBitValue(int &$value, int $index, bool $newBitValue): int {
  42. my_Assert($index >= 0 && $index <= 31, "index is Out Of Range(0..31)."); //索引出错
  43. $val = 1 << $index;
  44. $value = $newBitValue ? ($value | $val) : ($value & ~$val);
  45. return $value;
  46. }
  47. }