# Decimal to binary with limited fractional and exponent bits

I am trying to show the binary representation of a couple numbers using scientific notation. Using 8 bits for the fractional part, and 4 bits for the exponent. The exponent is stored using 2's compliment so if the exponent is negative I have to encode it properly.

So, I converted

2.71828182845 to 0 0010 10101101
and
-.0524289     to 1 0000 00001110


They should be correct, but now I am struggling to convert 15672.1334. Since 15672 is much larger than what a 4 bit exponent part can represent. I thought of turning it into 15.6721334*10^3, which would be 0 1111 10101100*10^3. But it doesn't seem right.

You have to be more carefull with how exactly you define your binary representation. The basic idea is to represent some value $x$ as $$x = (-1)^s \cdot m\cdot 10^e$$ and store it as a triple $(s,m,e)$ where one bit is allocated to $s$, $8$ to $m$ and $4$ to $e$. The format of $s$ is simple enough - $1$ means the value is negative, $0$ means it's positive. The format of $e$ is also relatively simple - per your question, you store the exponent as a signed 2's-complement integer. For $m$, however, your question is a bit ambiguous.

You can treat $m$ simply as an unsigned 8-bit integer (though calling it the "fractional part" is very missleading then!). In this case, $$\begin{eqnarray} 2.71828182845 &\to& (0,27,-1) \equiv 0\,|\,00011011\,|\,1111 \\ 2.71828182845 &\approx& (-1)^0\cdot 27 \cdot 10^{-1} = 2.7 \end{eqnarray}$$

Or you can interpret $m$ as a number within $[0,2.55)$, which comes down to always subtracting $2$ from the stored exponent. In this case $$\begin{eqnarray} 2.71828182845 &\to& (0,27,1) \equiv 0\,|\,00011011\,|\,0001 \\ 2.71828182845 &\approx& (-1)^0\cdot 27 \cdot 10^{-2}\cdot 10^{1} = 2.7 \end{eqnarray}$$

Or (better!) you can interpret $m$ as a number within $[0,1)$, in which case $$\begin{eqnarray} 2.71828182845 &\to& (0,0.271828182845*256,1) = (0,70,1) \equiv 0\,|\,01000110\,|\,0001 \\ 2.71828182845 &\approx& (-1)^0\cdot 70\cdot\frac{1}{256} \cdot 10^{1} = 2.734375 \end{eqnarray}$$

In fact, since we can always normalize $m$ to lie within $[0.1,1)$ (if it's less than $0.1$, just pick a smaller exponent), we might as well do $$\begin{eqnarray} 2.71828182845 &\to& (0,(0.271828182845-0.1)\frac{2560}{9},1) = (0,49,1) \equiv 0\,|\,01000101\,|\,0001 \\ 2.71828182845 &\approx& (-1)^0\cdot \left(0.1 + 49\cdot\frac{9}{2560}\right) \cdot 10^{1} = 2.72265625 \end{eqnarray}$$