Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
749 views
in Technique[技术] by (71.8m points)

algorithm - How to convert decimal fractions to hexadecimal fractions?

So I was thinking, how do you convert a decimal fraction into a hexadecimal fraction? What are some methods for converting and are there short cuts?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...