/ Published in: C
Expand |
Embed | Plain Text
// Convert number 'amount' to written English words // In short scale // Requires C99 for uint64_t // Supports large 64-bit integer number up to 18,446,744,073,709,551,615 #include <stdio.h> #include <stdlib.h> #include <stdint.h> const char* decades[] = {"", "", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"}; const char* digits[] = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTTEEN", "NINETEEN"}; typedef enum {QUINTILLION, QUADRILLION, TRILLION, BILLION, MILLION, THOUSAND, HUNDRED} Numeral; const char* Numeral_Names[] = {"QUINTILLION", "QUADRILLION", "TRILLION","BILLION", "MILLION", "THOUSAND", "HUNDRED"}; const uint64_t Numeral_Values[] = {1000000000000000000, 1000000000000000, 1000000000000, 1000000000, 1000000, 1000, 100}; void appendstr(char** pstr, const char* append) { register char c; while (1) { c = *append++; if (c == '') break; *(*pstr)++ = c; } } void write(uint64_t amount, char** pstr) { for (uint64_t n = QUINTILLION; n <= HUNDRED; n++) { if (amount < Numeral_Values[n]) continue; write(amount / Numeral_Values[n], pstr); appendstr(pstr, " "); appendstr(pstr, Numeral_Names[n]); appendstr(pstr, " "); amount %= Numeral_Values[n]; } if (amount > 20) { appendstr(pstr, decades[amount / 10]); amount %= 10; if (amount != 0) appendstr(pstr, "-"); else return; } appendstr(pstr, digits[amount]); } void written_amount(uint64_t amount, char* buffer) { write(amount, &buffer); *buffer = ''; } uint64_t rand64() { // Combin 4 parts of low 16-bit of each random() uint64_t R0 = (uint64_t)random() << 48; uint64_t R1 = (uint64_t)random() << 48 >> 16; uint64_t R2 = (uint64_t)random() << 48 >> 32; uint64_t R3 = (uint64_t)random() << 48 >> 48; return R0 | R1 | R2 | R3; } int main (int argc, char const *argv[]) { for (int i=0; i < 20; i++) { uint64_t amount = rand64(); amount >>= (20 - i) * 3; // scale numbers char buffer[1024] = { 0 }; written_amount(amount, buffer); } return 0; }
You need to login to post a comment.
