I need to convert binary float to decimal float in Mathematica, ideally between any two bases.
FromDigits["1.111111", 2]
does not work.
You need to get the RealDigits
first:
FromDigits[RealDigits[1.111111], 2]
This gives (after N
) 1.98438
which matches the value solved for here.
If you want to work between any two bases, say you wanted to know how to write the number 18 in hex:
FromDigits[RealDigits[18, 16]]
(* Out[]:= 12 *)
Alternatively, if you just want to "know" what the number is, without needing to compute with it, you can use BaseForm
:
BaseForm[18, 16]
If I understand correctly what you are looking for this may help:
FromDigits[{{1, 1, 1, 1, 1, 1, 1}, 1}, 2]
(*
=> 1.984,,,,
*)
The format given as input to FromDigits
is seen in the Documentation for RealDigits
.
To convert a real number in base less than 10 to base 10, you can use Eli's method. However, suppose you want to convert the number a1.34dc
in base 16 to base 10, then Eli's method doesn't work anymore. One workaround is to extract the decimal point from the string representing the number, convert the string using FromDigits
and multiply by an appropriate factor, e.g.
realTransform[str_String, b0_] := Module[{p, int, digits},
p = StringPosition[str, ".", 1];
int = FromDigits[
If[Length[p] == 1, StringDrop[str, p[[1, {1}]]], str], b0];
If[Length[p] > 0, int = N@int/b0^(StringLength[str] - p[[1, 1]])];
int]
realTransform["ab.bcf", 16]
(* ==> 171.738 *)
Complementing the other good answers. If you aren't looking for anything programatic, the following may help.
As to inputting a number in any base, you can type base^^number
.
So, for example, 2^^1.111111
returns 1.98438
.
If you want to see a number's representation in another base you can use, e.g, BaseForm[2^^1.111, 4]