CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jun 2001
    Location
    USA
    Posts
    298

    floating point to fixed and back

    I have an application that will stuff fixed point values into CPU registers. They're 32 bit (4 byte) and specified as:

    Unsigned fixed-point number: 5 bits integer 27 bits fractional
    Min = 0x0 = 0.0000000
    Max = 0xFFFFFFFF = 31.9999995

    How would I convert a number like 1.003936 to 4 bytes? Would also know how to go the other way.
    Can use either C++ or C#

    TIA

  2. #2
    Join Date
    Nov 2018
    Posts
    120

    Re: floating point to fixed and back

    You just multiply it with whatever 1.0 is in fixed point notation.

    Code:
    typedef unsigned int frac;
    
    frac one = 0x08000000;  // a single 1 followed by 27 zeros
    double v = 1.003936;
    frac result = v * one;

  3. #3
    Join Date
    Jun 2001
    Location
    USA
    Posts
    298

    Re: floating point to fixed and back

    You can't get an unsigned int result by multiplying one with a double. And if you cast the result all you get is "one".

  4. #4
    Join Date
    Nov 2018
    Posts
    120

    Re: floating point to fixed and back

    Did you even read the post?

    Code:
    $ cat foo.c
    #include <stdio.h>
    
    int main ( ) {
      typedef unsigned int frac;
      frac one = 0x08000000;  // a single 1 followed by 27 zeros
      double v = 1.003936;
      frac result = v * one;
      printf("%lf in frac = %#08x\n", v, result);
      return 0;
    }
    $ ./a.out 
    1.003936 in frac = 0x8080f98

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured