<?php
/**
* Binary Conversion Functions
* Created by: Joshua H. (TRUSTAbyss)
*
* These two functions allow you to convert
* decimal numbers to binary, or binary strings
* to decimal. An example on the proper use of
* these functions is shown below.
*
* [Example Usage]
* Decimal to Binary: dec2bin(173)
* Binary to Decimal: bin2dec('1101')
*
* NOTE: PHP already includes built-in functions
* for binary conversions. I wrote these so you're
* not stuck with PHP's functions.
*
* Provided by: http://www.trustabyss.com/
*/
function dec2bin($decimal = 0)
{
$binString = '';
$bit_number = 0;
$i = 0;
while ($bit_number <= $decimal)
{
$bit_number =
pow(2,
$i);
$base_table[] = $bit_number;
$i++;
}
$last_index =
count($base_table) -
1;
unset($base_table[$last_index]);
foreach ($base_table as $bitPosition)
{
if ($decimal >= $bitPosition)
{
$decimal -= $bitPosition;
$binString .= '1';
}
else
{
$binString .= '0';
}
}
{
$zero_padding = '';
for ($i =
0;
$i <
(8 -
strlen($binString));
$i++
) {
$zero_padding .= '0';
}
$binString = $zero_padding.$binString;
}
return $binString;
}
function bin2dec($binString = '00000000')
{
$decimal = 0;
$bin_array = str_split($binString, 1);
for ($i =
count($bin_array) -
1;
$i >=
0;
$i--
) {
$base_table[] =
pow(2,
$i);
}
for ($i =
0;
$i <
count($bin_array);
$i++
) {
if ($bin_array[$i] == '1')
{
$decimal += $base_table[$i];
}
}
return $decimal;
}
?>