BitBuffer.php 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /**
  3. *
  4. * @filesource BitBuffer.php
  5. * @created 25.11.2015
  6. * @package codemasher\QRCode
  7. * @author Smiley <smiley@chillerlan.net>
  8. * @copyright 2015 Smiley
  9. * @license MIT
  10. */
  11. namespace codemasher\QRCode;
  12. /**
  13. * Class BitBuffer
  14. */
  15. class BitBuffer{
  16. /**
  17. * @var array
  18. */
  19. public $buffer = [];
  20. /**
  21. * @var int
  22. */
  23. public $length = 0;
  24. /**
  25. * @return string
  26. */
  27. public function __toString(){
  28. $buffer = '';
  29. for($i = 0; $i < $this->length; $i++){
  30. $buffer .= (string)(int)(($this->buffer[(int)floor($i / 8)] >> (7 - $i % 8))&1) === 1;
  31. }
  32. return $buffer;
  33. }
  34. /**
  35. * @param $num
  36. * @param $length
  37. */
  38. public function put($num, $length){
  39. for($i = 0; $i < $length; $i++){
  40. $this->putBit((($num >> ($length - $i - 1))&1) === 1);
  41. }
  42. }
  43. /**
  44. * @param $bit
  45. */
  46. public function putBit($bit){
  47. $bufIndex = floor($this->length / 8);
  48. if(count($this->buffer) <= $bufIndex){
  49. $this->buffer[] = 0;
  50. }
  51. if($bit){
  52. $this->buffer[(int)$bufIndex] |= (0x80 >> ($this->length % 8));
  53. }
  54. $this->length++;
  55. }
  56. }