Skip to content

Instantly share code, notes, and snippets.

@sw17ch
Created May 15, 2014 16:23
Show Gist options
  • Select an option

  • Save sw17ch/533407c8d1a95062e87d to your computer and use it in GitHub Desktop.

Select an option

Save sw17ch/533407c8d1a95062e87d to your computer and use it in GitHub Desktop.
#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("%01d %03d %07d\n", sign, exp, fra);
printf("(-1)^%d * 2^(%d-127) * (1 + (%d / 2^23))\n", sign, exp, fra);
return 0;
}
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
static const uint64_t SIGN_MASK = 0x8000000000000000;
static const uint64_t EXP_MASK = 0x7ff0000000000000;
static const uint64_t FRA_MASK = 0x000fffffffffffff;
int main(int argc, char * argv[]) {
if (argc < 2) {
fprintf(stderr, "Please provide a float to parse.\n");
return -1;
}
double source;
sscanf(argv[1], "%lf", &source);
uint64_t * y = (uint64_t*)&source;
const bool sign = (*y & SIGN_MASK) >> 63;
const uint16_t exp = (*y & EXP_MASK) >> 52;
const uint64_t fra = (*y & FRA_MASK);
printf("%.45f\n", source);
printf("%01d %04d %016lld\n", sign, exp, fra);
printf("(-1)^%d * 2^(%d-127) * (1 + (%lld / 2^52))\n", sign, exp, fra);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment