Johannes Jensen Johannes Jensen - 1 year ago 44
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?


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:

    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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download