Jump to content

Extracting singel digits from an int.

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
Christine

Christine

    Newbie

  • Members
  • Pip
  • 1 posts
I want to be able to extract separate digits from a numbe. Lets say the year is 1981 then i want to be able to put the digit 9 in a variable, then I also want to be able to put the whole number in an variable.

How can I do this?

#2
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,720 posts
Use the modulus base ten of the number after removing the preceding digits.

[HIGHLIGHT="C++"]
int extractDigit(int number, int place)
{
for(int i = 0; i < place; ++i)
number /= 10; //get rid of the preceding digits
return number % 10; //now ignore all of the following ones
}
[/HIGHLIGHT]

To make it more generic, so that you can extract hex digits, just replace the tens with a variable called radix that'll be passed in as an argument.

#3
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
Adding to dargueta's response: the key to extracting digits is using integer and modular division. You could directly access the 9 in 1981 with (1981 / 100) % 10. The reason this works is that 1981/100 = 19, and 19 % 10 = 9.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog