Skip to content

Instantly share code, notes, and snippets.

@rasgo-cc
Last active August 29, 2015 14:23
Show Gist options
  • Save rasgo-cc/c2fb701a17c390e7175c to your computer and use it in GitHub Desktop.
Save rasgo-cc/c2fb701a17c390e7175c to your computer and use it in GitHub Desktop.
Fixed-Point Multiplication
// http://theramblingness.com
#include <stdio.h>
#include <stdint.h>
#define Qn 31
int main()
{
// Variables
uint32_t scaler = (uint32_t)(1<<Qn);
int64_t tmp = 0;
int32_t op1 = 0, op2 = 0;
int32_t res;
double res_f;
double f_val = 0.123456;
double f_res = f_val*f_val;
op1 = (int32_t)(f_val*(double)scaler);
op2 = op1;
printf("f_val: %f\n", f_val);
printf("f_res: %f\n", f_res);
printf("Qn: %u\n", Qn);
printf("scaler: %u\n", scaler);
printf("op: %d\n", op1);
printf("Fixed-point multiplication: op^2\n");
// Multiplication
tmp = (int64_t)op1*(int64_t)op2;
// Rounding
tmp = tmp + (int64_t)(1 << Qn);
// Truncation
tmp = tmp >> Qn;
// Discard the upper-half bytes of tmp to get the final result
res = (int32_t) tmp;
res_f = (double)res/(double)scaler;
printf("res: %d (%f)\n", res, res_f);
printf("err: %f\n", res_f - f_res);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment