Skip to content

Instantly share code, notes, and snippets.

@jessestricker
Created October 30, 2017 20:14
Show Gist options
  • Save jessestricker/c6f1a9e2b30f5b3333e8939fb1c2cf91 to your computer and use it in GitHub Desktop.
Save jessestricker/c6f1a9e2b30f5b3333e8939fb1c2cf91 to your computer and use it in GitHub Desktop.
GSP: Print integer values with a specific scale
#include <stdint.h>
#include <stdio.h>
void print_int(const int64_t v) {
const bool neg = v < 0;
uint64_t pv = neg ? -v : v;
// convert into digit characters
static const size_t DIGITS_LENGTH = 19;
char digits[DIGITS_LENGTH];
size_t end = 0;
for (size_t i = 0; i < DIGITS_LENGTH; i++) {
if (pv < 10) {
digits[i] = pv;
end = i;
break;
}
digits[i] = pv % 10;
pv /= 10;
}
// print to stdout
if (neg) putchar('-');
if (end == 0) putchar('0');
for (int i = end; i >= 0; i--) {
if (i == 0) putchar(',');
putchar(digits[i] + '0');
}
}
int main() {
print_int(-11); putchar('\n');
print_int(-10); putchar('\n');
print_int(-9); putchar('\n');
print_int(-1); putchar('\n');
print_int(0); putchar('\n');
print_int(1); putchar('\n');
print_int(9); putchar('\n');
print_int(10); putchar('\n');
print_int(11); putchar('\n');
print_int(19); putchar('\n');
print_int(111); putchar('\n');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment