0
votes

I'm trying to convert decimal numbers with commas into binary. I've seen that if you have for example the number 5.2 in decimal you convert it to 101.10, since 5 is 101 and 2 is 10 but I've seen a method that I don't quite understand.

For example, the number 93.3125 is 0000 0101 1101 0101. Why ? Are there other methods that help you transform decimals with comma into binary ?

2

2 Answers

1
votes

There are a multitude of ways to convert a decimal number into a string of 1s and 0s. You have just demonstrated two of them.

If you convert the number (represented in base-10 place notation) 93.3125 into "binary" (represented in base-2 place notation) you get 1011101.0101

If you convert it into a a binary floating-point format used in a computer language, you get a string of 1s and 0s, perhaps with a leading bit indicating sign, and some other bits for exponent -- you'll need a format description document to decode it.

Translating "5.2" into "101.10" (translating the parts before and after the decimal point separately) is a new one on me, and it is not a mathematically correct translation of place notation. "5"=>"101" is correct, but ".2"=>".10" is not; ".2" in decimal is two tenths, a.k.a. one fifth, which in base two is ".001100110011..." (one fifth is a repeating decimal in base two, just as one third is a repeating decimal in base ten.) And how would you translate "1.02"?

So yes, there are plenty of ways to encode a number in binary. Different codes are useful in different ways.

1
votes

You need to handle each part (before and after decimal point) separately. The integer part is converted by consequent division by base and the decimal part by consequent multiplying by base. In your case base = 2:

5.2 dec -> 5 + 0.2 dec

Integer part

5 % 2 = 1 // binary digit
5 / 2 = 2 // leftover for next iteration

2 % 2 = 0 // binary digit
2 / 2 = 1 // leftover for next iteration

1 % 2 = 1 // binary digit
1 / 2 = 0 // leftover for next iteration

Do not forget that the digits has to be used in reverse order (your 5 is the same however):

5 dec = 1 0 1 bin

Decimal part

0.2 * 2 = 0.4   
0.4 * 2 = 0.8   
0.8 * 2 = 1.6
0.6 * 2 = 1.2
0.2 * 2 = 0.4
...

All is in decadic. The integer part of result is your digit (in order) and the decimal part is leftover for next iteration. So the result is:

0.2 dec = 0 . 0 0 1 1 0 ... bin

Putting together:

5.2 dec = 101.00110... bin