Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

c - 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(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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You use the modulo operator:

while(score)
{
    printf("%d
", 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...