Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is log base 10 used in this code to convert int to string?

Tags:

c

string

int

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?

like image 203
STL34 Avatar asked Dec 03 '22 17:12

STL34


1 Answers

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.)

like image 93
ikegami Avatar answered Mar 07 '23 22:03

ikegami