How to convert decimal fractions to hexadecimal fractions?

You can use this algorithm:

  1. Take a fractional part of the number (i.e. integer part equals to zero)
  2. Multiply by 16
  3. Convert integer part to hexadecimal and put it down
  4. Go to step 1

For instance, let’s find out hexadecimal representation for pi = 3.141592653589793

integer part is evident – 0x3; as for fractional part (0.141592653589793) we have

  0.14159265358979 * 16 =  2.26548245743664; int part  2 (0x2); frac 0.26548245743664
  0.26548245743664 * 16 =  4.24771931898624; int part  4 (0x4); frac 0.24771931898624
  0.24771931898624 * 16 =  3.96350910377984; int part  3 (0x3); frac 0.96350910377984
  0.96350910377984 * 16 = 15.41614566047744; int part 15 (0xF); frac 0.41614566047744
  0.41614566047744 * 16 =  6.65833056763904; int part  6 (0x6); frac 0.65833056763904
  0.65833056763904 * 16 = 10.53328908222464; int part 10 (0xA); ...

So pi (hexadecimal) = 3.243F6A

Possible (C#) implementation

public static String ToHex(Double value) {
  StringBuilder Sb = new StringBuilder();

  if (value < 0) {
    Sb.Append('-');

    value = -value;
  }

  // I'm sure you know how to convert decimal integer to its hexadecimal representation
  BigInteger bi = (BigInteger) value;
  Sb.Append(bi.ToString("X"));

  value = value - (Double)bi;

  // We have integer value in fact (e.g. 5.0)
  if (value == 0)
    return Sb.ToString();

  Sb.Append('.');

  // Double is 8 byte and so has at most 16 hexadecimal values
  for (int i = 0; i < 16; ++i) {
    value = value * 16;
    int digit = (int) value;

    Sb.Append(digit.ToString("X"));

    value = value - digit;

    if (value == 0)
      break;
  }

  return Sb.ToString();
}

Test

   Console.Write(ToHex(Math.PI)); // <- returns "3.243F6A8885A3"

Leave a Comment