Getting each individual digit from a whole integer

Johannes Jensen picture Johannes Jensen · Jun 25, 2010 · Viewed 97.7k times · Source

Let's say I have an integer called 'score', that looks like this:

int score = 1529587;

Now what I want to do is get each digit 1, 5, 2, 9, 5, 8, 7 from the score using bitwise operators(See below edit note).

I'm pretty sure this can be done since I've once used a similar method to extract the red green and blue values from a hexadecimal colour value.

How would I do this?

Edit
It doesn't necessarily have to be bitwise operators, I just thought it'd be simpler that way.

Answer

Martin B picture Martin B · Jun 25, 2010

You use the modulo operator:

while(score)
{
    printf("%d\n", score % 10);
    score /= 10;
}

Note that this will give you the digits in reverse order (i.e. least significant digit first). If you want the most significant digit first, you'll have to store the digits in an array, then read them out in reverse order.