# Algorithm to convert real numbers decimal to binary

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!

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

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"

• Or ToString@Row@Insert[#1, ".", #2 + 1] & @@ RealDigits[#, 2] &[41.213]. Commented Mar 25, 2022 at 15:33
• Please try your code with myNum=0.213.
– Syed
Commented Mar 26, 2022 at 5:47
• 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.
– josh
Commented Mar 26, 2022 at 10:02