简体   繁体   中英

What is the most efficient (speed) way to get a digit from a larger number?

I plan to use this inside a game loop to draw the score using custom bitmap font.

Here is what I have. Now I know that I have used the modulus, division and power operators a bunch of times. I understand that using this in a game loop is not a good thing to do. Any suggestions?

// Get digit n, where n is digit starting from the units place and moving left

int getDigit(int number, int position)
{
    return (number % (int)pow(10, position)) / pow(10, (position - 1));
}

If int is 32 bits, then:

static const int table[] =
    { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
return number / table[position-1] % 10;

is a reasonable implementation:

  • It does not invoke pow or use floating-point arithmetic.
  • It uses one table look-up, one division by a variable, and one remainder operation with a constant (which a compiler can optimize to a multiplication and some shifts and adds).

(Note that position is adjusted in the table lookup to be one-based to match the code in the question, but common practice would be to call the units position position 0 instead of position 1.)

If digits are to be extracted for multiple positions or the whole number, then other implementations should be considered.

You said that you extract a digit in order to display the game score; so I assume you will use the whole original number.

You can extract all the digits in a loop this way:

int number = 1234;  // this variable will be consumed

while (number) {
  rightmostdigit = number % 10;
  // do something with the extracted digit
  number /= 10;  // discard the rightmost at go to the next
}

The above routine extracts digits from the right, so the score shall be drawn from right to left. Warning that if the number is zero, the loop is never executed...

If you want to extract from left, and supposing a fixed-length score (like "00123"), you can store the single digits in an array, then read them back in the inverse direction: it should be faster than trying to extract the digits from left to right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM