0 Replies - 1211 Views - Last Post: 15 February 2012 - 06:14 AM Rate Topic: -----

#1 Aphex19  Icon User is offline

  • Born again Pastafarian.
  • member icon

Reputation: 618
  • View blog
  • Posts: 1,873
  • Joined: 02-August 09

Approximating a decimal fraction in binary

Posted 15 February 2012 - 06:14 AM

Description: Compiles under GCC.This code calculates the fractional part of a decimal number with arbitrary precision (up to 32-bits). C floats are used for arithmetic purposes, although the integer portion is ignored. Note that the resultant binary value does not conform to any floating point standard (such as IEEE 754), it just gives the value "as is".
#include <stdio.h>

/* calculates a fractional binary approximation to a 
   given decimal value with up to 32-bit precision */
unsigned int CalcFraction(int precision, float fval) {
	fval = fval - (int)fval;
	float frac = 0.5;
	unsigned int fbin = 0;
	int i;
	
	for (i = precision-1; i >= 0; i--) {
		if (fval / frac >= 1.0) {
			fbin |= (1 << i);
			fval -= frac;
		}
		frac /= 2;
	}
	return fbin;
}

int main() {
	printf("%Xn", CalcFraction(16, .249939));
	return 0;
}


Is This A Good Question/Topic? 0
  • +

Page 1 of 1