Sunday, 22 December 2013 11:00

## Count number of digits in a number and extract each digit

Written by
Count number of digits in a number(integer). Eg. countDigits(5678) return 4
`byte countDigits(int num){  byte count=0;  while(num){    num=num/10;    count++;  }  return count;}`

Extract a digit from an number(integer). Eg. getDigit(5678,2) return 6
`int getDigit(unsigned int number, int digit) {    for (int i=0; i<digit-1; i++) {       number /= 10;     }    return number % 10;}`

Extract all digits from a number and store them to an array
`#define MAX_NUMBER_OF_DIGITS 5byte array_to_hold_digit[MAX_NUMBER_OF_DIGITS]; void setup(void) {  Serial.begin(9600);  extractDigit_Save2Arrary(5678);  Serial.println(array_to_hold_digit[0]);  Serial.println(array_to_hold_digit[1]);  Serial.println(array_to_hold_digit[2]);  Serial.println(array_to_hold_digit[3]);} void loop(void) { } /*---------------------------------------------------------------------------- count number of digits in a number(integer)----------------------------------------------------------------------------*/void extractDigit_Save2Arrary(int number){  byte number_of_digit = countDigits(number);   for (byte i=0; i<number_of_digit; i++) {       array_to_hold_digit[i] = getDigit(number,number_of_digit-i); //store each digit to array  }   /*  for (byte i=0; i<number_of_digit; i++) {       Serial.print(array_to_hold_digit[i]);  }  Serial.println();  */} /*---------------------------------------------------------------------------- count number of digits in a number(integer)----------------------------------------------------------------------------*/byte countDigits(int number){  byte count=0;  while(number){    number=number/10;    count++;  }  return count;} /*---------------------------------------------------------------------------- extract a digit from an number(integer)----------------------------------------------------------------------------*/byte getDigit(unsigned int number, int digit) {    for (int i=0; i<digit-1; i++) {       number /= 10;     }    return number % 10;}`

Read 19994 times Last modified on Sunday, 22 December 2013 11:43