View previous topic :: View next topic |
Author |
Message |
Guest
|
I want extract the single digit from a int8: |
Posted: Sat Aug 09, 2008 2:51 am |
|
|
Hi
I want extract the single digit from a int8:
169 I want c1=1/c2=6/c3=9
I made this func for testing. Working but not nice.
Code: | void Get_Digit(void){
//want to isolate the digit
//ex. 169: c1=9/c2=6/c3=1
int t,c1,c2,c3,tmp;
t=169;
//any hints for optimizing
c1=t%10;
c2=(t-c1)/10%10;
c3=(t-(t%100))/100;
tmp= c1+c2*10+c3*100;
printf("t:%u c1:%u c2:%u c3:%u tmp:%u",t,c1,c2,c3,tmp);
} |
Any suggestion? |
|
|
SherpaDoug
Joined: 07 Sep 2003 Posts: 1640 Location: Cape Cod Mass USA
|
|
Posted: Sat Aug 09, 2008 6:15 am |
|
|
What you have is fine. If you must go a little faster you can subtract in a loop instead of dividing. It will save a few machine cycles but the code is harder to understand so I don't recommend it unless timing is crucial. _________________ The search for better is endless. Instead simply find very good and get the job done. |
|
|
Indy
Joined: 16 May 2008 Posts: 24
|
|
Posted: Sat Aug 09, 2008 5:01 pm |
|
|
If you use an array instead of 3 separate variables you could do it like: Code: | int8 c[3];
int8 value = 169;
for (i=3; i>0; i--)
{
c[i-1] = value % 10;
value = value / 10;
} |
|
|
|
Guest
|
|
Posted: Sun Aug 10, 2008 2:12 am |
|
|
:-) |
|
|
languer
Joined: 09 Jan 2004 Posts: 144 Location: USA
|
|
Posted: Mon Aug 11, 2008 1:03 am |
|
|
If you only want to display digits, you can use sprintf.
Code: | char c[4];
sprintf(c,"%u",value); |
|
|
|
|