QRBitBuffer.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. /**
  3. * This file is part of the phpQr package
  4. *
  5. * See @see QRCode class for description of package and license.
  6. */
  7. /**
  8. * QRBitBuffer class
  9. *
  10. * The purpose of this class is to act as data holder for QRCode.
  11. *
  12. * @author Maik Greubel <[email protected]>
  13. * @package phpQr
  14. */
  15. class QRBitBuffer
  16. {
  17. /**
  18. * Array based buffer access
  19. *
  20. * @var array
  21. */
  22. private $buffer;
  23. /**
  24. * Length of array
  25. *
  26. * @var int
  27. */
  28. private $length;
  29. /**
  30. * Create a new instance of QRBitBuffer
  31. */
  32. public function __construct()
  33. {
  34. $this->buffer = array();
  35. $this->length = 0;
  36. }
  37. /**
  38. * Get particular bit given by index
  39. *
  40. * @param int $index The index of bit
  41. * @return boolean
  42. */
  43. public function get($index)
  44. {
  45. $bufIndex = floor($index / 8);
  46. return ( ($this->buffer[$bufIndex] >> (7 - $index % 8) ) & 1) == 1;
  47. }
  48. /**
  49. * Get the byte at particular index
  50. *
  51. * @param int $index The index of the byte
  52. * @return string
  53. */
  54. public function getAt($index)
  55. {
  56. return $this->buffer[$index];
  57. }
  58. /**
  59. * Put amount of bits
  60. * @param int $num The data to put
  61. * @param int $length The length of data
  62. */
  63. public function put($num, $length)
  64. {
  65. for($i = 0; $i < $length; $i++)
  66. {
  67. $this->putBit((($num >> ($length - $i - 1)) & 1) == 1);
  68. }
  69. }
  70. /**
  71. * Get current length in bits
  72. *
  73. * @return int The amount of bits
  74. */
  75. public function getLengthInBits()
  76. {
  77. return $this->length;
  78. }
  79. /**
  80. * Put particular bit
  81. *
  82. * @param int $bit The bit to put
  83. */
  84. public function putBit($bit)
  85. {
  86. $bufIndex = floor($this->length / 8);
  87. if(sizeof($this->buffer) <= $bufIndex)
  88. {
  89. array_push($this->buffer, 0);
  90. }
  91. if($bit)
  92. {
  93. $this->buffer[$bufIndex] |= (0x80 >> ($this->length % 8));
  94. }
  95. $this->length++;
  96. }
  97. }