Wednesday, May 14, 2008

number of digits in int64


Share at Facebook

Last time I have given an example of how to use an __int64 number at gcc or vc6 here http://icfun.blogspot.com/2008/04/use-of-int64-variable-in-c.html. Today I'm going to explain how to find the number of digits from a given int64 number. This is easy. Just follow the below example.

#include<stdio.h>
#include<string.h>

int main(){
__int64 i = 1099897826746536290;
char digits[30];
sprintf(digits,"%I64d\n",i);
printf("Digits : %d\n",strlen(digits)-1);
return 0;
}
Above example what I did is, just print the __int64 number into an string using sprint function. And using strlen of string library just find the length of the string.




1 comment:

Eddy Luten said...

Hi there.

You don't have to call any STL functions to achieve this functionality, see the amtDigits function below. (PS, your blog doesn't accept the HTML PRE tag).

#include <stdio.h>

// The actual function which counts the
// digits in the long long (__int64)
unsigned int amtDigits(long long i64cnt)
{
unsigned int count;
for ( count = 0; i64cnt; count++ )
i64cnt /= 10;
return count;
}

int main ( void )
{
// EXAMPLE CODE:
__int64 bigInt1 = 12345678901234567; // 17 count
__int64 bigInt2 = 12345; // 5 count
__int64 bigInt3 = 1234567890123456789; // 19 count

printf("Digits: %d\n", amtDigits(bigInt1) );
printf("Digits: %d\n", amtDigits(bigInt2) );
printf("Digits: %d\n", amtDigits(bigInt3) );
return 0;
}