smerny Posted October 7, 2009 Share Posted October 7, 2009 bindec() ignores decimal points... for example, it converts .101 to 5 Link to comment https://forums.phpfreaks.com/topic/176783-solved-php-function-to-convert-fractional-binarys-to-base10/ Share on other sites More sharing options...
corbin Posted October 7, 2009 Share Posted October 7, 2009 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. Link to comment https://forums.phpfreaks.com/topic/176783-solved-php-function-to-convert-fractional-binarys-to-base10/#findComment-932110 Share on other sites More sharing options...
smerny Posted October 7, 2009 Author Share Posted October 7, 2009 is there a way to remove the "0."? that way I could explode(".",1.1) for example, and use bindec on the first part and your method on the second part, and then put them togehter like part[0] .".". part[1] Link to comment https://forums.phpfreaks.com/topic/176783-solved-php-function-to-convert-fractional-binarys-to-base10/#findComment-932123 Share on other sites More sharing options...
smerny Posted October 7, 2009 Author Share Posted October 7, 2009 actually i suppose i could just add them, lol Link to comment https://forums.phpfreaks.com/topic/176783-solved-php-function-to-convert-fractional-binarys-to-base10/#findComment-932126 Share on other sites More sharing options...
smerny Posted October 7, 2009 Author Share Posted October 7, 2009 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 Link to comment https://forums.phpfreaks.com/topic/176783-solved-php-function-to-convert-fractional-binarys-to-base10/#findComment-932132 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.