back to embedded

C String to Int

 

unsigned int toint(unsigned char *inval, BYTE count){
    unsigned char i, v;
    unsigned int temp, outval=0;
    
    for(i=0; i<count; i++){
        temp = *inval;
        //increment pointer to next character in the string
        inval++;
        temp -= 0x30;
        if(temp > 0){
            for(v=i; v<(count-1); v++){
                temp *= 10;
            }
        }
        /*
        //ensure that the value does not exceed 65535 otherwise return 65535
        if(outval + temp > 65535){
            return 65535;
        }
        */
        outval += temp;
    }
    return outval;
}
    

 

Takes the input of a char pointer string of length count and converts the human readable value into an integer. This is very useful when manually controlling a device through a serial port.

 

Usage:
unsigned char value[25] = "1475";
unsigned int intValue = toint(value, 4);