print_internal_uint64_t compressed table

Run Settings
LanguageC++
Language Version
Run Command
#include <stdio.h> #include <stdint.h> #include <string.h> #include <assert.h> #include <stdlib.h> typedef struct { // UINT64_MAX is 20 bytes. char view_8[21]; } Print_Buffer; uint8_t length_table[22] = { 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 19, }; uint64_t limit_table[22] = { 10, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000, 10000000000, 100000000000, 1000000000000, 10000000000000, 100000000000000, 1000000000000000, 10000000000000000, 100000000000000000, 1000000000000000000, 10000000000000000000UL, 10000000000000000000UL, }; size_t count_leading_zeros(uint64_t v) { if(v == 0) { return 64; } return __builtin_clzl(v); } void print_internal_uint64_t(uint64_t v, uint32_t *length = 0) { Print_Buffer output = {0}; uint8_t string_length = 1; if(v != 0) { size_t table_index = (63LL - count_leading_zeros(v)) / 3; //printf("|%zu|", table_index); //exit(0); //printf("%llu|%zu|", v, count_leading_zeros(v)); string_length = length_table[table_index]; if(v >= limit_table[table_index]) { string_length += 1; } } size_t i = 0; while(true) { i += 1; output.view_8[string_length - i] = (v % 10) + '0'; v /= 10; if(v == 0) { break; } } assert(string_length - i == 0); if(length) { *length = i; } //printf("%zu|", i); printf("%s\n", output.view_8); } void print_n(uint64_t v) { printf("uint64_t: "); print_internal_uint64_t(v); } void print_n(int64_t v) { printf("int64_t: "); if(v < 0) { printf("-"); v = -v; } print_internal_uint64_t(v); } uint64_t pow10(uint64_t count) { uint64_t result = 1; for(size_t i = 0; i < count; ++i) { result *= 10; } return result; } int main() { uint32_t len_bah = 0; print_internal_uint64_t(0, &len_bah); //printf("\n"); #if 0 for(size_t i = 0; i < 64; i += 3) { //printf("%.2zu ", i / 3); uint32_t length_small = 0; print_internal_uint64_t(1UL << i, &length_small); //printf("|"); //printf("%.2zu ", i); uint32_t length_large = 0; print_internal_uint64_t((1UL << i << 3) - 1, &length_large); //printf("\n"); uint64_t limit = 0; limit = pow10(length_small); //printf("\t%u,\n", length_small); //printf("\t%lu,\n", limit); //printf("%u, %lu\n", length_small, limit); //printf("\tString_Length_Table { %u, %lu },\n", length_small, limit); //printf("-- %i\n", (int)(i * 0.3 + 1.3)); } #endif for(size_t i = 0; i < 64; i += 1) { print_internal_uint64_t(1UL << i); print_internal_uint64_t((1UL << i << 1) - 1); } printf("--\n"); print_n(UINT64_MAX); print_n(18446744073709551); print_n(0UL); print_n(1UL); print_n(9UL); print_n(50UL); print_n(62UL); print_n(73L); print_n(-84L); print_n(99999999L); print_n(100000000L); print_n(45645656L); print_n(35123123123L); print_n(4564565645645656L); print_n(99L); print_n(100L); return 0; }
Editor Settings
Theme
Key bindings
Full width
Lines