Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more efficient way of splitting a number into its digits?

I have to split a number into its digits in order to display it on an LCD. Right now I use the following method:

pos = 7;

do
{
    LCD_Display(pos, val % 10);
    val /= 10;
    pos--;
} while (pos >= 0 && val);

The problem with this method is that division and modulo operations are extremely slow on an MSP430 microcontroller. Is there any alternative to this method, something that either does not involve division or that reduces the number of operations?

A note: I can't use any library functions, such as itoa. The libraries are big and the functions themselves are rather resource hungry (both in terms of number of cycles, and RAM usage).

like image 605
alex Avatar asked Feb 10 '12 08:02

alex


People also ask

How do you break a number into an array?

To do this: Convert the number to a string. Call the split() method on the string to convert it into an array of stringified digits. Call the map() method on this array to convert each string to a number.


1 Answers

You could do subtractions in a loop with predefined base 10 values.

My C is a bit rusty, but something like this:

int num[] = { 10000000,1000000,100000,10000,1000,100,10,1 };

for (pos = 0; pos < 8; pos++) {
  int cnt = 0;
  while (val >= num[pos]) {
    cnt++;
    val -= num[pos];
  }
  LCD_Display(pos, cnt);
}
like image 58
Guffa Avatar answered Oct 24 '22 02:10

Guffa