Johannes Jensen Johannes Jensen - 9 months ago 28
C Question

Getting each individual digit from a whole integer

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. 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 Source

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.