BitUtils.php 906 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. <?php
  2. declare(strict_types = 1);
  3. namespace BaconQrCode\Common;
  4. /**
  5. * General bit utilities.
  6. *
  7. * All utility methods are based on 32-bit integers and also work on 64-bit
  8. * systems.
  9. */
  10. final class BitUtils
  11. {
  12. private function __construct()
  13. {
  14. }
  15. /**
  16. * Performs an unsigned right shift.
  17. *
  18. * This is the same as the unsigned right shift operator ">>>" in other
  19. * languages.
  20. */
  21. public static function unsignedRightShift(int $a, int $b) : int
  22. {
  23. return (
  24. $a >= 0
  25. ? $a >> $b
  26. : (($a & 0x7fffffff) >> $b) | (0x40000000 >> ($b - 1))
  27. );
  28. }
  29. /**
  30. * Gets the number of trailing zeros.
  31. */
  32. public static function numberOfTrailingZeros(int $i) : int
  33. {
  34. $lastPos = strrpos(str_pad(decbin($i), 32, '0', STR_PAD_LEFT), '1');
  35. return $lastPos === false ? 32 : 31 - $lastPos;
  36. }
  37. }