Skip to content

Instantly share code, notes, and snippets.

@mcclure
Last active November 9, 2021 03:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcclure/f02a1b3d7b29697f3748a35fbfc60d08 to your computer and use it in GitHub Desktop.
Save mcclure/f02a1b3d7b29697f3748a35fbfc60d08 to your computer and use it in GitHub Desktop.
// Helper program translates from decimal numbers to C99 "%a" format.
// Arguments:
// -r : Translate %a to decimal instead
// -d : Use doubles
// Then enter numbers you want to convert one line at a time
//
// To compile just do: gcc percenta.c
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <float.h>
#ifndef FLT_DECIMAL_DIG
// Oops we're in C++
#include <limits>
#define FLT_DECIMAL_DIG (std::numeric_limits<float>::max_digits10)
#define DBL_DECIMAL_DIG (std::numeric_limits<double>::max_digits10)
#endif
bool check(int result) {
if (result == 0) {
printf("Unrecognized\n");
while (1) {
int ch = getchar();
if (ch == '\n' || ch == '\r' || ch == EOF)
return false;
}
}
return true;
}
int main(int argc, const char **argv) {
bool reverse = false, doubled = false;
int arg = 1;
while (arg < argc) {
if (strcmp(argv[arg], "-r") == 0)
reverse = true;
else if (strcmp(argv[arg], "-d") == 0)
doubled = true;
else {
printf("Usage: %s [-r] [-d])\n", argv[0]);
}
arg++;
}
if (doubled) {
if (reverse) {
while (1) {
double f = 0;
int found = scanf("%la", &f);
if (found == EOF)
break;
if (check(found))
printf("%.*lg\n", DBL_DECIMAL_DIG, f);
}
} else {
while (1) {
double f = 0;
int found = scanf("%lf", &f);
if (found == EOF)
break;
if (check(found))
printf("%la\n", f);
}
}
} else {
if (reverse) {
while (1) {
float f = 0;
int found = scanf("%a", &f);
if (found == EOF)
break;
if (check(found))
printf("%.*g\n", FLT_DECIMAL_DIG, f);
}
} else {
while (1) {
float f = 0;
int found = scanf("%f", &f);
if (found == EOF)
break;
if (check(found))
printf("%a\n", f);
}
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment