Advertisement

Simple modulus question

Started by February 24, 2001 10:30 AM
3 comments, last by Insomnia 23 years, 11 months ago
Hey all, Sorry, I know this question has been asked at one time or another, but I cant find the post i''m looking for which explained it. Essentially, I need to extract a single digit from an integer. I''m pretty sure I could do it somehow with the modulus operator, but i''m not sure how. Also, if there are alternative methods, which one would be the fastest? I need to do this every frame, so the faster the better . Cheers Insomnia
Insomnia
The modulus is slow but if you're only getting one digit - the last one then it's pretty fast.

Last Digit: 6598 % 10 = 8

Extract the Nine: 6598 % 100 = 98 / 10 = 9.8 -> convert to int by dropping the .8

Extract the Five: 6598 % 1000 = 598 / 100 = 5.98 -> convert to int by dropping the .98

Extracting the Six: 6598 / 1000 = 6.598 -> convert to int by dropping the .598



Regards,
Jumpster

Edit: Here's a quick inline for you... Lot's of math so it ain't neccessarily fast...

__inline byte GetDigit( int source, int which)
{
if (which < 1) return -1; // Error...
if (which == 1) return (byte) source % 10;
else
{
// What's the base power that we need...?
return (byte) (((source % (int) pow(10,which-1)) % 10);
}

//////////////////////////////////////
// Should NEVER end here but just in
// case flag as a Serious Error...
return -2;
}



Edited by - Jumpster on February 24, 2001 12:19:51 PM
Regards,JumpsterSemper Fi
Advertisement
Thanks for the reply Jumpster, I had a feeling that was the solution, but I was praying for a faster one . Thanks anyway!

[EDIT] Thanks for adding the inline function too . I'll probably use it, simply because the method i'm using at the moment is ugly as hell . Thanks again!

Insomnia

Edited by - Insomnia on February 24, 2001 12:43:36 PM
Insomnia
Here''s another less mathematical way to do it, heh.
int GetDigit(int number, int digit) {  char str[11];  sprintf(str,"%d",number);  if(str[0]!=''-'') digit--;  return (str[digit]-''0'');} 


"Finger to spiritual emptiness underlying everything." -- How a C manual referred to a "pointer to void." --Things People Said
Resist Windows XP''s Invasive Production Activation Technology!
http://www.gdarchive.net/druidgames/
GetDigit (int num, int pos)
{
// num = XNY -> XN
for (i = pos; i >= 0; i--) {
num /= 10;
}
// num = XN -> N
return num % 10;
}

----
The speed of this is proportional to the value of pos.

Edited by - GayleSaver on February 24, 2001 10:42:35 PM
VK

This topic is closed to new replies.

Advertisement