Reputation: 11
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));
}
Upvotes: 0
Views: 593
Reputation: 4704
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.
Upvotes: 0
Reputation: 223702
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:
pow
or use floating-point arithmetic.(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.
Upvotes: 1