basically I want to return the number of digits in the int -> values like this:
(int)1 => 1
(int)123 => 3
(int)12345678 => 8
I know nothing about C, so please bear with me. I know objective c, but I use ints and floats instead of NSNumbers. I realise I could convert the ints into objective c objects, but this seems faffy, and if I can do it with C I'll know it for the future.
Thanks
As you know, the best way to find the length of a string is by using the strlen() function.
The length of an integer means the total number of digits present in that integer. We can find the length of integer by using the following approaches: Using while loop. Using String.
strlen wouldn't work too well for integers, simply because of the way integers are stored. Assuming 32bit ints, they take four bytes (16 bit integers will use 2 bytes) and for Windows PC's they stored in little endian format - the least significant byte of the integer value will occupy the lowest address.
String Length in C Using Built-In Library Function The length of a string can be found using the built-in library function strlen() in string. h header file. It returns the length of the string passed to it (ignoring the null character). The string is passed to the strlen() function, which returns its length.
use
int d = (value == 0 ? 1 : (int)(log10(value)+1));
Note that this doesnt work for negative numbers, you'll have to use
int d = (value == 0 ? 1 : ((int)(log10(fabs(value))+1) + (value < 0 ? 1 : 0)));
which adds 1 for the minus sign, if value
is negative.
Probably much faster than using log or int-to-string conversion and without using any library functions is this:
int nDigits(int i)
{
if (i < 0) i = -i;
if (i < 10) return 1;
if (i < 100) return 2;
if (i < 1000) return 3;
if (i < 10000) return 4;
if (i < 100000) return 5;
if (i < 1000000) return 6;
if (i < 10000000) return 7;
if (i < 100000000) return 8;
if (i < 1000000000) return 9;
return 10;
}
EDIT after Jeff Yates concerns:
For those who worry about int sizes different from 32-bits (similar to pmg's solution but still faster because multiplication is faster than division :-)
#include <limits.h>
#define PO10_LIMIT (INT_MAX/10)
int nDigits(int i)
{
int n,po10;
if (i < 0) i = -i;
n=1;
po10=10;
while(i>=po10)
{
n++;
if (po10 > PO10_LIMIT) break;
po10*=10;
}
return n;
}
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