Press "Enter" to skip to content

How to convert decimals to binary

Ajk 0

Today we are going to take a look at a fun little question and learn how to convert decimals to binary 🙂

First off, to clarify any confusion we have from the term “decimal”:

  • We have the Decimal Number System – which is any number in base 10.
  • We also have a Decimal Number – which is just a floating point number, for this we will use the more correct mathematical term rational numbers.
  • Finally we have Decimal Part – which is the fractional part of a number, or the one after the floating point.

Now, as an accomplished software engineer you must know by now how to convert integers from base 10 to base 2, but what happens when we are trying to cover all rational numbers?

How to Convert Decimals To Binary – Brainstorm

Let’s think about how to approach this problem. Since we know how to convert the integer part, we should focus on how to convert the decimal part.
What does the decimal part of a number represent in binary. By analogy on the decimal number system:

  • Decmal Number System – 0.101 = 1/101 + 0/102 +1/103
  • Binary Number System – 0.101 = 1/21 + 0/22 +1/23

So to shift the floating point in binary we just need to multiply by 2. We can easily do this action in decimal too. And since we only have two cases for binary (0 or 1), we can infer that if the total value of our number multiplied by 2, is greater than 1, then we would have a 1 after the floating point in binary, otherwise a 0.

Let us start to write code for this:

How to Convert Decimals To Binary – Java

Check the notes on our how to convert decimals to binary implementation in Java:

  1. We used a StringBuffer instead of a String, since we continuously change the String and we do not want to create a new object every time.
  2. We used a bit-shift >>= 1, instead of a division by 2, since for most CPUs bit shifting is faster.
  3. We could not use bit-shifting for floating point numbers, since they have a different representation than integers.

Hope you enjoyed the writing, now you should know how to convert decimals to binary… and I’ll see you guys next time 🙂

The following two tabs change content below.
If you like one of my posts the best way to support is give it a thumbs up, comment, or share it on social media 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *