Search code examples
algorithmfloating-pointdecimal-pointradixradix-point

How do you calculate floating point in a radix other than 10?


Given Wikipedia's article on Radix Point, how would one calculate the binary equivalent of 10.1 or the hex equivalent of 17.17? For the former, what is the binary equivalent of a tenth? For the latter, the hex representation of 17/100?

I'm looking more for an algorithm than for solutions to just those two examples.


Solution

  • To convert decimal 10.1 to binary, separate the integer and fractional parts and convert each separately.

    To convert the integer part, use repeated integer division by 2, and then write the remainders in reverse order:

    10/2 = 5 remainder 0

    5/2 = 2 remainder 1

    2/2 = 1 remainder 0

    1/2 = 0 remainder 1

    Answer: 1010

    To convert the fractional part, use repeated multiplication by 2, subtracting off the integer part at each step. The integer parts, in order of generation, represent your binary number:

    0.1 * 2 = 0.2

    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

    0.4 * 2 = 0.8

    ... (cycle repeats forever)

    So decimal 0.1 is binary 0.000110011001100...

    (For a more detailed explanation see routines dec2bin_i() and dec2bin_f() in my article http://www.exploringbinary.com/base-conversion-in-php-using-bcmath/ .)

    For hexadecimal, use the same procedure, except with a divisor/multiplier of 16 instead of 2. Remainders and integer parts greater than 9 must be converted to hex digits directly: 10 becomes A, 11 becomes B, ... , 15 becomes F.