pb_base128.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. /**
  3. * Base 128 varints - decodes and encodes base128 varints to/from decimal
  4. * @author Nikolai Kordulla
  5. */
  6. class base128varint
  7. {
  8. // modus for output
  9. var $modus = 1;
  10. /**
  11. * @param int $modus - 1=Byte 2=String
  12. */
  13. public function __construct($modus)
  14. {
  15. $this->modus = $modus;
  16. }
  17. /**
  18. * @param $number - number as decimal
  19. * Returns the base128 value of an dec value
  20. */
  21. public function set_value($number)
  22. {
  23. $string = decbin($number);
  24. if (strlen($string) < 8)
  25. {
  26. $hexstring = dechex(bindec($string));
  27. if (strlen($hexstring) % 2 == 1)
  28. $hexstring = '0' . $hexstring;
  29. if ($this->modus == 1)
  30. {
  31. return $this->hex_to_str($hexstring);
  32. }
  33. return $hexstring;
  34. }
  35. // split it and insert the mb byte
  36. $string_array = array();
  37. $pre = '1';
  38. while (strlen($string) > 0)
  39. {
  40. if (strlen($string) < 8)
  41. {
  42. $string = substr('00000000', 0, 7 - strlen($string) % 7) . $string;
  43. $pre = '0';
  44. }
  45. $string_array[] = $pre . substr($string, strlen($string) - 7, 7);
  46. $string = substr($string, 0, strlen($string) - 7);
  47. $pre = '1';
  48. if ($string == '0000000')
  49. break;
  50. }
  51. $hexstring = '';
  52. foreach ($string_array as $string)
  53. {
  54. $hexstring .= sprintf('%02X', bindec($string));
  55. }
  56. // now format to hexstring in the right format
  57. if ($this->modus == 1)
  58. {
  59. return $this->hex_to_str($hexstring);
  60. }
  61. return $hexstring;
  62. }
  63. /**
  64. * Returns the dec value of an base128
  65. * @param string bstring
  66. */
  67. public function get_value($string)
  68. {
  69. // now just drop the msb and reorder it + parse it in own string
  70. $valuestring = '';
  71. $string_length = strlen($string);
  72. $i = 1;
  73. while ($string_length > $i)
  74. {
  75. // unset msb string and reorder it
  76. $valuestring = substr($string, $i, 7) . $valuestring;
  77. $i += 8;
  78. }
  79. // now interprete it
  80. return bindec($valuestring);
  81. }
  82. /**
  83. * Converts hex 2 ascii
  84. * @param String $hex - the hex string
  85. */
  86. public function hex_to_str($hex)
  87. {
  88. $str = '';
  89. for($i = 0; $i < strlen($hex); $i += 2)
  90. {
  91. $str .= chr(hexdec(substr($hex, $i, 2)));
  92. }
  93. return $str;
  94. }
  95. }
  96. ?>