Skip to main content

Computer Architecture

Handling Decimals in Hardware: A Closer Look 🧐

Decimal numbers are fundamental data types in many computational applications, including embedded systems. Understanding how these numbers are stored in the memory is crucial for developing efficient and accurate algorithms in the embedded domain.

This post talks about how the decimal numbers are actually stored in the memory.

So how are the decimals stored?

There are two different types of notations to store decimal numbers in the memory. The first one is floating-point notation, and the other is fixed-point notation.

Let's start with floating-point notation!

Consider a floating-point number 10.75. Let’s go step by step and understand how 10.75 is actually stored in the memory.

Step 1: Convert floating-point number to binary format

In 10.75 , the integral part is 10 and the decimal part is 0.75.

The binary representation of 10 would be 1010. To get the binary representation of 0.75 we need to follow these steps:  

0.75 * 2 = 1.50      // Take 1 form this and move 0.50 to the next step.

0.50 * 2 = 1.00    // Take 1 and stop here, since there is no remainder.

Ever wonder, why we need to multiply the decimal/fractional part with 2 and take out 1/0, to convert it to equivalent binary?

To understand this we need to understand how the fractional numbers are represented in binary number system. Let’s take a fractional number in binary as abc.pqr, now to convert this to decimal, we do:

(a x 2^2) + (b x 2^1) + (c x 2^0) . (p x 2^-1) + (q x 2^-2) + (r x 2^-3)

From the above expression, it is clear that we are summing up the decimal part by multiplying it with 2^-n to convert from binary to decimal. Similarly, when we do the backward process (converting from decimal to binary), we multiple the decimal part with 2, which is easier than dividing by 1/2^n and then finding out the remainder every time.

The reason behind taking 1 or 0 out every time we multiply the decimal number with 2 is simple. This is because in binary, we have only two digits, 0 and 1. If the result of the multiplication is greater than or equal to 1, we know that the power of 2 corresponding to that position contributes to the decimal fraction, so we take 1. Otherwise, if the result is less than 1, we know that the power of 2 does not contribute to the decimal fraction, so we take 0.

Okay! now let us continue our calculation. 😀