3
$\begingroup$

I am trying to define a function which takes a binary number and gives the decimal form. I tried the following

binarytodecimal[b_] := NumberForm[2^^b, 20]

But the variable b is not recognised by Mathematica, I think because of the ^^. I have tried reading the documentation to see if there is another way to input a binary number but I haven't found anything.

As an example, take 0.0100101010101010101010. Then NumberForm[2^^0.0100101010101010101010, 20] computes but trying to turn this into a function does not work.

Is there a way around this?

$\endgroup$
9
  • $\begingroup$ In what format are you providing the binary number? As an ordinary "decimal" number (b = 1011001) or as a string (b = "1011001") or as a list of digits (b = {1, 0, 1, 1, 0, 0, 1}). $\endgroup$
    – Domen
    Commented Aug 16, 2021 at 10:22
  • 2
    $\begingroup$ FromDigits[RealDigits[0.0100101010101010101010, 10], 2] gives 611669/2097152 and using N gives 0.291667 $\endgroup$
    – flinty
    Commented Aug 16, 2021 at 10:35
  • 2
    $\begingroup$ @math, I think this double caret is some very low-level syntactic "thing", which cannot be evaluated together with other symbols, but only with numerical symbols (i.e. numerals, decimal point and letters). For example: b = 1101; 2^^b does not work. $\endgroup$
    – Domen
    Commented Aug 16, 2021 at 10:44
  • 1
    $\begingroup$ Following my comment, in the open-source parser for Wolfram Language (line 1051), you can see that base^^digits gets tokenized as a single token, and therefore this double caret is not a proper "symbol" or "operator". $\endgroup$
    – Domen
    Commented Aug 16, 2021 at 10:52
  • 1
    $\begingroup$ @math, very good question. indeed. $\endgroup$
    – Syed
    Commented Aug 16, 2021 at 12:56

1 Answer 1

4
$\begingroup$

The code

binarytodecimal[b_String] := NumberForm[ToExpression["2^^"<>b], 20];

does what you want. For example

binarytodecimal["0.0100101010101010101010"]

evaluates to 0.2916665077209473

$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.