By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,116 Members | 1,509 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,116 IT Pros & Developers. It's quick & easy.

C: Splitting an integer number into digits?

P: 45
I'm working on a PIC project, and my brain has almost exploded! I'm hoping that by writing down my problem, that the answer will come to me, but please feel free to help!

Background (mostly irrelevant to an outsider): I'm storing a number in a variable (say r, an unsigned integer) which represents the ratio of a pulley system. The ratio itself is a real number and unlikely to be an integer, but I need to store it as an integer for storage reasons (not relevant to this discussion). When used, the integer will be divided by a constant (probably 4000) and the result will be used via a cast to a float.

In order for the user to set the value of the integer (using select and increment buttons), I have to first display it using 3 single variables (d1, d10, d100) that represent each digit up to 1000, then the thousands (and possible tens of thousands) as another variable (d1000).

For example, r = 32768 is comprised of:

d1000 = 32
d100 = 7
d10 = 6
d1 = 8

Getting d1000 is easy, it's just r/1000. For d100 I considered (r-(1000*d1000))/100 which is OK, but it gets messy after that. I'm guessing there is a way of doing this with remainders, but my brain is too hot.

[Later] Well, it didn't work, I'm still stuck. Anyone care to help?


PS I'm over 50, this is not homework!
Sep 11 '10 #1
Share this Question
Share on Google+
1 Reply

Expert Mod 5K+
P: 8,916
Use an extra variable and the modulus (%) operator. Note this is not a wildly efficient operator sometimes. The extra variable is used because the value in it is destroyed and I am assuming you want to keep the value in r intact. Something like this:

Expand|Select|Wrap|Line Numbers
  1. unsigned r = 32768;
  2. unsigned temp = r;
  3. unsigned d1000;
  4. unsigned d100;
  6. d1000 = temp / 1000;
  7. temp %= 1000;
  8. d100 = temp / 100;
  9. temp %= 100;
  10. /* etc */
Sep 11 '10 #2

Post your reply

Sign in to post your reply or Sign up for a free account.