Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 501
Johannes Jensen Avatar asked Jun 25 '10 13:06

Johannes Jensen


People also ask

How do you divide an integer into an individual digit?

You can convert a number into String and then you can use toCharArray() or split() method to separate the number into digits.

How do you find the number of digits in an integer?

Perhaps the easiest way of getting the number of digits in an Integer is by converting it to String, and calling the length() method. This will return the length of the String representation of our number: int length = String. valueOf(number).


2 Answers

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.

like image 62
Martin B Avatar answered Sep 28 '22 19:09

Martin B


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

like image 26
David M Avatar answered Sep 28 '22 19:09

David M