Skip to content

Instantly share code, notes, and snippets.

@sw17ch
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save sw17ch/66df04f020d997db2130 to your computer and use it in GitHub Desktop.

Select an option

Save sw17ch/66df04f020d997db2130 to your computer and use it in GitHub Desktop.
/*
* http://en.wikipedia.org/wiki/Single_precision_floating-point_format
*/
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
static const uint32_t SIGN_MASK = 0x80000000;
static const uint32_t EXP_MASK = 0x7f800000;
static const uint32_t FRA_MASK = 0x007fffff;
int main(int argc, char * argv[]) {
if (argc < 2) {
fprintf(stderr, "Please provide a float to parse.\n");
return -1;
}
float source;
sscanf(argv[1], "%f", &source);
uint32_t * y = (uint32_t*)&source;
const bool sign = (*y & SIGN_MASK) >> 31;
const uint8_t exp = (*y & EXP_MASK) >> 23;
const uint32_t fra = (*y & FRA_MASK);
printf("%.45f\n", source);
printf("%d %d %d\n", sign, exp, fra);
printf("(-1)^%d * 2^(%d-127) * (1 + (%d / 2^23))\n", sign, exp, fra);
return 0;
}
@sw17ch

sw17ch commented May 15, 2014

Copy link
Copy Markdown
Author
CornSyrup:~ ./expanded_float 1
1.000000000000000000000000000000000000000000000
0 127 0
(-1)^0 * 2^(127-127) * (1 + (0 / 2^23))
CornSyrup:~ ./expanded_float 0.1
0.100000001490116119384765625000000000000000000
0 123 5033165
(-1)^0 * 2^(123-127) * (1 + (5033165 / 2^23))
CornSyrup:~ ./expanded_float 0.0000000000001
0.000000000000099999998245167004418121337039338
0 83 6368787
(-1)^0 * 2^(83-127) * (1 + (6368787 / 2^23))

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