Go Down

Topic: convert int to string and then... (Read 2 times) previous topic - next topic

donde

I want to convert 3 digit integer like, 354 to string so to dig out each character (number) to convert back to integer. I'll use each number to show on single 7 segment LCD, sequentially, delay about 250ms. I already know how to show on display.

Not sure how to make 3 digits a string array, to get at each character, like char[0], char[1], char[2], and then convert each array element back to an integer to use in display.

PaulS

Quote
I want to convert 3 digit integer like, 354 to string so to dig out each character (number) to convert back to integer.


You could use itoa() to convert the value to a string, and then subtract '0' from each character in the array to get the number, in each place, but division and modulo will be faster.
Code: [Select]
int n = 354;
int h = n / 100; // h = 3
int t = (n / 10) % 10; // 354 / 10 = 35. 35%10 = 5
int o = n % 100; // 354 % 100 = 4

donde

Quote
but division and modulo will be faster.
Code:


I was kind of thinking of modulo, but WOW thanks for jelling my thought! Your example looks good. Thanks.

donde

Well, the last statement didn't work.
It should be:  int o = (n % 100)  % 5;                                 // 354 % 100 % 5 = 4

I should have stated, not for just 354, but for any number. So, I guess I should look into itoa()

Arrch

#4
Oct 10, 2012, 11:18 pm Last Edit: Oct 10, 2012, 11:21 pm by Arrch Reason: 1

Well, the last statement didn't work.
It should be:  int o = (n % 100)  % 5;                                 // 354 % 100 % 5 = 4

I should have stated, not for just 354, but for any number. So, I guess I should look into itoa()



That won't work either:

Code: [Select]
359 % 100 % 5 = 4

There was a small typo in PaulS' post. What you need is

Code: [Select]
int o = n % 10

Go Up