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
  1. byte countDigits(int num){
  2. byte count=0;
  3. while(num){
  4. num=num/10;
  5. count++;
  6. }
  7. return count;
  8. }
 
 
Extract a digit from an number(integer). Eg. getDigit(5678,2) return 6
  1. int getDigit(unsigned int number, int digit) {
  2. for (int i=0; i<digit-1; i++) {
  3. number /= 10;
  4. }
  5. return number % 10;
  6. }
 
 
Extract all digits from a number and store them to an array
  1. #define MAX_NUMBER_OF_DIGITS 5
  2. byte array_to_hold_digit[MAX_NUMBER_OF_DIGITS];
  3.  
  4. void setup(void) {
  5. Serial.begin(9600);
  6. extractDigit_Save2Arrary(5678);
  7. Serial.println(array_to_hold_digit[0]);
  8. Serial.println(array_to_hold_digit[1]);
  9. Serial.println(array_to_hold_digit[2]);
  10. Serial.println(array_to_hold_digit[3]);
  11. }
  12.  
  13. void loop(void) {
  14.  
  15. }
  16.  
  17. /*----------------------------------------------------------------------------
  18.  count number of digits in a number(integer)
  19. ----------------------------------------------------------------------------*/
  20. void extractDigit_Save2Arrary(int number){
  21. byte number_of_digit = countDigits(number);
  22. for (byte i=0; i<number_of_digit; i++) {
  23. array_to_hold_digit[i] = getDigit(number,number_of_digit-i); //store each digit to array
  24. }
  25.  
  26. /*
  27.   for (byte i=0; i<number_of_digit; i++) {
  28.   Serial.print(array_to_hold_digit[i]);
  29.   }
  30.   Serial.println();
  31.   */
  32. }
  33.  
  34. /*----------------------------------------------------------------------------
  35.  count number of digits in a number(integer)
  36. ----------------------------------------------------------------------------*/
  37. byte countDigits(int number){
  38. byte count=0;
  39. while(number){
  40. number=number/10;
  41. count++;
  42. }
  43. return count;
  44. }
  45.  
  46. /*----------------------------------------------------------------------------
  47.  extract a digit from an number(integer)
  48. ----------------------------------------------------------------------------*/
  49. byte getDigit(unsigned int number, int digit) {
  50. for (int i=0; i<digit-1; i++) {
  51. number /= 10;
  52. }
  53. return number % 10;
  54. }
 
 
Read 9245 times Last modified on Sunday, 22 December 2013 11:43

Leave a comment

Back to Top