views:

128

answers:

4

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.

+8  A: 

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.

Martin B
I'm pretty sure modulo is not a bitwise operator
Scorpi0
@Scorpi0: No, it isn't... but there's no sensible way to do this using bitwise operators, and I think this is what the OP was looking for.
Martin B
i think what OP meant hexadecimal and it is possible to solve with bitwise.
Andrey
@Andrey from the example it's clear OP is asking about decimal digits.
Geoff
Nice method! This was what I needed, thanks :)
Johannes Jensen
+4  A: 

RGB values fall nicely on bit boundaries; decimal digits don't. I don't think there's an easy way to do this using bitwise operators at all. You'd need to use decimal operators like modulo 10 (% 10).

David M
+1 He's right, decimal (base 10) numbers do not partition on bits (base 2), except for numbers that are powers of 2 (like 256 = 2^8 for colors). Since 10 is not a power of 2, you will not be able to use bitwise operators.
Geoff
+2  A: 

Agree with previous answers.

A little correction: There's a better way to print the decimal digits from left to right, without allocating extra buffer. In addition you may want to display a zero characeter if the score is 0 (the loop suggested in the previous answers won't print anythng).

This demands an additional pass:

int div;
for (div = 1; div <= score; div *= 10)
    ;

do
{
    div /= 10;
    printf("%d\n", score / div);
    score %= div;
} while (score);
valdo
+2  A: 

Don't reinvent the wheel. C has sprintf for a reason. Since your variable is called score, I'm guessing this is for a game where you're planning to use the individual digits of the score to display the numeral glyphs as images. In this case, sprintf has convenient format modifiers that will let you zero-pad, space-pad, etc. the score to a fixed width, which you may want to use.

R..
I like how you analyzed EXACTLY what I was going to use it for Thanks a lot!
Johannes Jensen