# Approximating a decimal fraction in binary

Page 1 of 1

## 0 Replies - 1506 Views - Last Post: 15 February 2012 - 06:14 AMRate Topic:     //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=364363&amp;s=fdf91151966d0aa9a8b76b0d5a87c07f&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 Aphex19 Reputation: 619
• 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

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }