-
Potentially useful code
I figured out a way to calculate the max number of digits in a base 10 integer using only the number of bits in said integer, here's my code:
Code:
// Calculate the number of base 10 digits #ifndef INT_BASE10_DIG #define INT_BASE10_DIG(BITS) (((((BITS)%3)==0)?(BITS):((BITS)+(3-((BITS)%3))))/3) #endif
I figured it out after looking at the numbers on a PC calculator in scientific binary mode and was appending 1s slowly and saw that after the total 1s moved above a divisor of 3 the number of decimal digits would go up. I gave the thread this title in case others wanted to add their own to it and end up with being a sticky thread edit: This can go in the same #ifdef to caculate the needed integer size
Code:
#define BASE10_INT_BIT(DIGS) ((DIGS)*3)+(CHAR_BIT-(((DIGS)*3)%CHAR_BIT))
-
I used this little piece of code:
Code:
#include <stdio.h>
#include <limits.h>
#define BASE10_INT_BIT(DIGS) ((DIGS)*3)+(CHAR_BIT-(((DIGS)*3)%CHAR_BIT))
int main(void)
{
int i;
printf("Binary | Decimal\n");
for (i = 1; i <= 16; i++) {
printf("%4d %4d\n", i, BASE10_INT_BIT(i));
}
return 0;
}
and I got these results:
Code:
Binary | Decimal
1 8
2 8
3 16
4 16
5 16
6 24
7 24
8 32
9 32
10 32
11 40
12 40
13 40
14 48
15 48
16 56
Those numbers don't seem right at all, unless I misunderstood what you're calculating.
EDIT: Is it backwards? I think I used it backwards. That macro seems to take the number of decimal digits and converts it into bits...
-
The actual number you need is given by log (10)ślog(2)
Which is approximately 3.32 binary bits for each decimal digit.
So if your approximation can manage that, you should be good :)
Don't forget the +1 in your approximation for storing a \0.