Skip to content

Instantly share code, notes, and snippets.

@yfuruyama
Last active October 11, 2024 08:58
Show Gist options
  • Save yfuruyama/8470448 to your computer and use it in GitHub Desktop.
Save yfuruyama/8470448 to your computer and use it in GitHub Desktop.
convert floating point number to fixed point number
#include <stdio.h>
#include <math.h>
#define FIXED_BIT 12
unsigned short int float2fix(float n)
{
unsigned short int int_part = 0, frac_part = 0;
int i;
float t;
int_part = (int)floor(n) << FIXED_BIT;
n -= (int)floor(n);
t = 0.5;
for (i = 0; i < FIXED_BIT; i++) {
if ((n - t) >= 0) {
n -= t;
frac_part += (1 << (FIXED_BIT - 1 - i));
}
t = t /2;
}
return int_part + frac_part;
}
int main()
{
float n;
n = 2.5; // 0d10240
printf("%f => %d\n", n, float2fix(n));
n = 2.625; // 0d10752
printf("%f => %d\n", n, float2fix(n));
n = 0.375; // 0d1536
printf("%f => %d\n", n, float2fix(n));
return 0;
}
@len0rd
Copy link

len0rd commented Aug 7, 2019

Thanks! If you want this to handle negative numbers, you need to check for it before setting int_part.
lines 11-12 should be like this:

  if (n > 0) {
    int_part = ((int)floor(n)) << FIXED_BIT;
  }
  else {
    int_part = ((int)ceil(n)) << FIXED_BIT; // need to round towards 0
  }
  // now that the whole part has been translated and set in 2s compliment, dont need to worry about sign
  n = fabs(n) - floor(fabs(n));

I also added some nan/inf checks to mine.

@zumpchke
Copy link

@len0rd can you explain what this does?


    t = 0.5;
    for (i = 0; i < FIXED_BIT; i++) {
        if ((n - t) >= 0) {
            n -= t;
            frac_part += (1 << (FIXED_BIT - 1 - i));
        }
        t = t /2;
    }

@len0rd
Copy link

len0rd commented Nov 26, 2019

Its converting the fractional portion of the float to fixed point. The fractional portion of fixed point is represented by 1/(2^(i+1)).

ie: for a 4-bit fixed point number, where 3 bits are a fraction, 0.75 -> 0110.

Here's some more stuff for you to look at:
http://www-inst.eecs.berkeley.edu/~cs61c/sp06/handout/fixedpt.html

@sponthus
Copy link

sponthus commented Aug 5, 2024

@len0rd Hello,
The article you linked is not accessible outside of berkeley, is it accessible somewhere else ?
Thank you for your help.

@len0rd
Copy link

len0rd commented Aug 5, 2024

@sponthus looks like they made that change sometime in the last 5 years since I posted. Here’s a working copy on the wayback machine

@sponthus
Copy link

sponthus commented Aug 5, 2024

Thanx that's perfect !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment