Jump to content

[SOLVED] php function to convert fractional binarys to base10?


smerny

Recommended Posts

Hrmmm, the easiest way seems to be:

 

 

//get the decimal part of the base 2 number and store it in $bd

 

Then:

 

$number = $bd * pow(2, -strlen($bd));

 

 

I can explain the math if you want.

 

 

(It's important to make sure that $bd keeps all digits by the way.  For example, if .01 goes to 1 instead of 01 it will be wrong.

this is what i ended up with:

 

echo $input . "<sub>two</sub><br />";

$parts = explode(".",$input);
$len = strlen($parts[0]);
$i = 0;
while($i < $len)
{
	$pow = $len - $i - 1;
	echo $parts[0][$i]."(2<sup>".$pow."</sup>)";
	if($pow != 0) { echo " + "; }
	$i++;
}
if($parts[1] != "")
{
	$len = strlen($parts[1]);
	$pow = -1;
	$i = 0;
	$deci = 0;
	while($i < $len)
	{
		echo " + ";
		echo $parts[1][$i]."(2<sup>".$pow."</sup>)";
		$deci += ($parts[1][$i])*pow(2,$pow);
		$i++;
		$pow--;
	}
}

echo "<br />Answer: ". bindec($parts[0]) + $deci . "<sub>ten</sub>";

 

sample output:

 

1011.1001two

1(23) + 0(22) + 1(21) + 1(20) + 1(2-1) + 0(2-2) + 0(2-3) + 1(2-4)

Answer: 11.5625ten

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.