Last active
October 11, 2024 08:58
-
-
Save yfuruyama/8470448 to your computer and use it in GitHub Desktop.
convert floating point number to fixed point number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
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
@len0rd Hello,
The article you linked is not accessible outside of berkeley, is it accessible somewhere else ?
Thank you for your help.
@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
Thanx that's perfect !
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@len0rd can you explain what this does?