0
$\begingroup$

Currently trying to write code that converts decimal floats to binary base form (I know BaseForm exists).

Currently I'm working with an example that takes 3.3 and converts it:

binary={}
x = Floor[3.3*2^8];
For[i = 0, i <= 9, i++,
  remainder = Mod[x, 2];
  x = Floor[x/2];
  AppendTo[binary, remainder];
  ];
Print[FromDigits[Reverse[binary]]]

Which gives: 1101001100

Obviously the answer should have a . between 11 and 01001100, but I'm not quite sure how to implement this. Does anyone have any ideas (so it would work with all examples, not just 3.3).

Thanks!

$\endgroup$
2
  • $\begingroup$ RealDigits[3.3, 2] and you can control the number of digits you want with the 3rd argument? $\endgroup$ Commented Mar 25, 2022 at 14:37
  • $\begingroup$ BaseForm[3.3, 2]? $\endgroup$
    – Michael E2
    Commented Mar 25, 2022 at 14:39

1 Answer 1

3
$\begingroup$

If you want just a string representing real num base2, extract the base-2 digits and base-2 exponent of the form {{digits},exponent} and then convert it to a string:

 myNum = 41.213;
    myB = RealDigits[myNum, 2]
    myBExp = myB[[2]]
    newFormat = 
     ToString@Row[myB[[1, 1 ;; myBExp]]] <> "." <> 
      ToString@Row[myB[[1, myBExp + 1 ;;]]]

Out[704]= {{1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1}, 6}

Out[706]= "101001.00110110100001110010101100000010000011000100101"

$\endgroup$
3
  • 2
    $\begingroup$ Or ToString@Row@Insert[#1, ".", #2 + 1] & @@ RealDigits[#, 2] &[41.213]. $\endgroup$
    – Michael E2
    Commented Mar 25, 2022 at 15:33
  • 1
    $\begingroup$ Please try your code with myNum=0.213. $\endgroup$
    – Syed
    Commented Mar 26, 2022 at 5:47
  • $\begingroup$ Ok. I'll leave that for you: Put an If statement in. If the exponent "myBExp" is negative (or zero?), then string together a "0" a "." then a total of Abs[myBExp] zeros, then add all the remaining digits of myB[[1]]. Something like leadingZeros=Table[0,{Abs[myBExp]]]. Then newFormat="0"<>"."<>ToString@Row[leadingZeros]<>ToString@Row[myB[[1]]]. You may have to work with it a bit to work with all possible cases including negative numbers. $\endgroup$
    – josh
    Commented Mar 26, 2022 at 10:02

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.