Splitting an integer
I need some assistance, I'm required to split an integer into its component parts, e.g if I have an integer of 46 I want to split it into 4 and 6. Any ideas how I might go about achieving this?
What have you tried?
Do you know how to do this, in discrete steps, manually?
I've got no idea where to start with this
This is basic math, I suggest you find an elementary (1st grade) math book. If you can't do this basic math without a computer you'll never be able to write the program.
unless i'm mistaken it isn't basic maths.... I need to send an integer a digit at a time over a serial port, so using the previous example if I want to send 46, I need to first send the 4 then the 6.
It's very basic integer math.
If you have the number 46, how would you manipulate it to get 6? You need to think integer, not floating-pointing point. It's what you learned back around 4th grade, that's how basic it is.
I'm clearly missing something here...... the only thing I can think you are meaning is for the example I could do 46-40=6 and (46-6)/10 if that's what you are meaning? if so that won't work as I don't know what the integers will be, (actually the values could be anything within several thousand either side of 0, so a lot of variation)
No need to subtract. Integer division will give you a quotient and a remainder. Though that requires two operations in C: division for the quotient and modulo for the remainder.
Since you don't know the size of the integer, you would need to whittle away at it from the 1's end. Take the remainder and save it (I would use an array), then divide the number (after the first step, it will be the quotient from the previous step that you will divide). Repeat until the quotient is zero. Keep a count of how many digits you got so that you can start with that last digit and work your way backwards through the array to output them.
July 10th, 2013, 06:25 PM
a basic approach would be:
first check if the number is<0, if so remember that so you can add a - sign to your number and then multiply it by -1, now it is positive.
next you loop until the number is zero
in each loop, do a modulo 10 (%10) instruction to find the lowest digit, and store this in a buffer, then divide the number by 10
when you are done, the result will be stored in the buffer in the wrong order, i.e. least significant digit first, so you will need to read it out to send it backwards, remembering to add the - sign if there is one
Alternatively call the itoa() function which does it all.