1. <?php
  2. /**
  3.  * Binary Conversion Functions
  4.  * Created by: Joshua H. (TRUSTAbyss)
  5.  *
  6.  * These two functions allow you to convert
  7.  * decimal numbers to binary, or binary strings
  8.  * to decimal. An example on the proper use of
  9.  * these functions is shown below.
  10.  *
  11.  * [Example Usage]
  12.  * Decimal to Binary: dec2bin(173)
  13.  * Binary to Decimal: bin2dec('1101')
  14.  *
  15.  * NOTE: PHP already includes built-in functions
  16.  * for binary conversions. I wrote these so you're
  17.  * not stuck with PHP's functions.
  18.  *
  19.  * Provided by: http://www.trustabyss.com/
  20.  */
  21.  
  22. function dec2bin($decimal = 0)
  23. {
  24. $binString = '';
  25. $base_table = array();
  26. $bit_number = 0;
  27. $i = 0;
  28.  
  29. while ($bit_number <= $decimal)
  30. {
  31. $bit_number = pow(2, $i);
  32. $base_table[] = $bit_number;
  33. $i++;
  34. }
  35.  
  36. $last_index = count($base_table) - 1;
  37.  
  38. unset($base_table[$last_index]);
  39. rsort($base_table);
  40.  
  41. foreach ($base_table as $bitPosition)
  42. {
  43. if ($decimal >= $bitPosition)
  44. {
  45. $decimal -= $bitPosition;
  46. $binString .= '1';
  47. }
  48. else
  49. {
  50. $binString .= '0';
  51. }
  52. }
  53.  
  54. if (strlen($binString) < 8)
  55. {
  56. $zero_padding = '';
  57.  
  58. for ($i = 0; $i < (8 - strlen($binString)); $i++)
  59. {
  60. $zero_padding .= '0';
  61. }
  62.  
  63. $binString = $zero_padding.$binString;
  64. }
  65.  
  66. return $binString;
  67. }
  68.  
  69. function bin2dec($binString = '00000000')
  70. {
  71. $decimal = 0;
  72. $bin_array = str_split($binString, 1);
  73. $base_table = array();
  74.  
  75. for ($i = count($bin_array) - 1; $i >= 0; $i--)
  76. {
  77. $base_table[] = pow(2, $i);
  78. }
  79.  
  80. for ($i = 0; $i < count($bin_array); $i++)
  81. {
  82. if ($bin_array[$i] == '1')
  83. {
  84. $decimal += $base_table[$i];
  85. }
  86. }
  87.  
  88. return $decimal;
  89. }
  90. ?>