I saw a post explaining how to convert an int to a string. In the explanation there is a line of code to get the number of chars in a string:
(int)((ceil(log10(num))+1)*sizeof(char))
I’m wondering why log base 10 is used?
ceil(log10(num))+1
is incorrectly being used instead of floor(log10(num))+2
.
The code is attempting to determine the amount of memory needed to store the decimal representation of the positive integer num
as a string.
The two formulas presented above are equal except for numbers which are exact powers of 10, in which case the former version returns one less than the desired number.
For example, 10,000 requires 6 bytes, yet ceil(log10(10000))+1
returns 5
. floor(log10(10000))+2
correctly returns 6.
How was floor(log10(num))+2
obtained?
A 4-digit number such as 4567 will be between 1,000 (inclusive) and 10,000 (exclusive), so it will be between 103 (inclusive) and 104 (exclusive), so log10(4567) will be between 3 (inclusive) and 4 (exclusive).
As such, floor(log10(num))+1
will return number of digits needed to represent the positive value num
in decimal.
As such, floor(log10(num))+2
will return the amount of memory needed to store the decimal representation of the positive integer num
as a string. (The extra char is for the NUL that terminates the string.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With