Continue to Site

Welcome to our site!

Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

  • Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

Converting Array to integer

Status
Not open for further replies.

bryan

Member
Hello All:

Would appreciate some help on converting the contents of an array to an integer. User enters data and it is stored into an array, but how can i convert the contents to an integer.

Here is what I have for adding the data to the array, until either 3 characters are entered from 0-9 or until the escape or enter key.

Say the user enters 1 and then enter, the array would be 100, or the user could enter 001 and then enter, the value is 1 but how to pull it out of the array so it is a number of 1. I suppose I could pad the array with FF and test each value in the array, and multiply the placeholders by 1,10,100 and add them together?. Any suggestions ?.



Code:
       unsigned char i;
	unsigned int array[3];
	unsigned char x; 


 do {
           while(!DataRdyUSART());       //polls receive buffer for available data
           i = ReadUSART();              // read a single character from buffer
      		 if ( ('0' <= i) && (i <= '9') && (x >=0) )
              {   
					 array[x]=i-Ascii;  //  Add to array
	 				 printf("%c",i,0);   //display on terminal;
					 x--;               
			  }
      		
   }  
   
    while ( 13 != i && 27 != i);
 
Last edited:
what if he enters something else, string for example?
 
can integer be negative?

if not you could do something like

Code:
        unsigned char i;
	//unsigned int array[3];
	unsigned char x; 
        int temp;
 
 do {
           temp=0;  // init temp as zero
           while(!DataRdyUSART());       //polls receive buffer for available data
           i = ReadUSART();              // read a single character from buffer
      		 if ( ('0' <= i) && (i <= '9') && (x >=0) )
              {   
				temp=temp*10;  // adding digit, multiply temp by 10 and then... 
                                temp=temp+ i - '0'; // add current digit               
			  }
 
   }  
 
    while ( 13 != i && 27 != i);
 
Thank you very much panic mode. That did the trick. So simple and efficient, can get rid of the array.
 
Status
Not open for further replies.

Latest threads

New Articles From Microcontroller Tips

Back
Top