1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <sys/types.h>
4 #include <sys/wait.h>
5 #include <unistd.h>
6 #include <errno.h>
7 #include <limits.h>
8 #include <math.h>
9 
10 #include "EXTERN.h"
11 #include "perl.h"
12 #include "ppport.h"
13 
14 static U32 len_table_u32[] = {
15   9, 99, 999, 9999,
16   99999, 999999, 9999999, 99999999,
17   999999999, UINT_MAX
18 };
19 
20 U8
uint32_length(U32 num)21 uint32_length(U32 num)
22 {
23   U8 i;
24   for (i = 0;; ++i) {
25     if (num < len_table_u32[i])
26       return i+1;
27   }
28 }
29 
30 #ifndef U64_CONST
31 # define U64_CONST(x) ((uint64_t)x##UL)
32 #endif
33 
34 static uint64_t len_table_u64[] = {
35   9, 99, 999, 9999,
36   99999, 999999, 9999999, 99999999,
37   U64_CONST(999999999),
38   U64_CONST(9999999999),
39   U64_CONST(99999999999),
40   U64_CONST(999999999999),
41   U64_CONST(9999999999999),
42   U64_CONST(99999999999999),
43   U64_CONST(999999999999999),
44   U64_CONST(9999999999999999),
45   U64_CONST(99999999999999999),
46   U64_CONST(999999999999999999),
47   U64_CONST(9999999999999999999),
48   U64_CONST(18446744073709551615)
49 };
50 
51 U8
uint64_length(uint64_t num)52 uint64_length(uint64_t num)
53 {
54   U8 i;
55   for (i = 0;; ++i) {
56     if (num < len_table_u64[i])
57       return i+1;
58   }
59 }
60 
61 
62 U8
uint64_length_2(uint64_t num)63 uint64_length_2(uint64_t num)
64 {
65   U8 len = 0;
66   unsigned int tmp = 1UL;
67   while(tmp < num)
68   {
69       ++len;
70       tmp = (tmp << 3) + (tmp << 1);
71   }
72   return len;
73 }
74 
75 U8
uint64_length_3(uint64_t num)76 uint64_length_3(uint64_t num)
77 {
78   return (U8)floor( log10( num ) ) + 1;
79 }
80 
81 #define CASE(n,i) if (num < (uint64_t)(n##UL)) return i
82 U8
uint64_length_4(uint64_t num)83 uint64_length_4(uint64_t num)
84 {
85   CASE(9, 1);
86   CASE(99, 2);
87   CASE(999, 3);
88   CASE(9999, 4);
89   CASE(99999, 5);
90   CASE(999999, 6);
91   CASE(9999999, 7);
92   CASE(99999999, 8);
93   CASE(999999999, 9);
94   CASE(9999999999, 10);
95   CASE(99999999999, 11);
96   CASE(999999999999, 12);
97   CASE(9999999999999, 13);
98   CASE(99999999999999, 14);
99   CASE(999999999999999, 15);
100   CASE(9999999999999999, 16);
101   CASE(99999999999999999, 17);
102   CASE(999999999999999999, 18);
103   CASE(9999999999999999999, 19);
104   return 20;
105 }
106 #undef CASE
107 
108 int
main(int argc,char ** argv)109 main(int argc, char** argv) {
110   unsigned int i = 0;
111 
112   for (i = 0; i < 300000000; ++i) {
113     uint64_length_4(i);
114   }
115 
116   return 1;
117 }
118