Search code examples
c++coctalleading-zero

How to convert const char* to uint16_t octal (C/C++)


I need to convert values with leading zero to octal. Because 12 (14 octal) is different from 012 (10 octal)

The function I will call requires a variable of type uint16_t and the value to be converted is received dynamically and can be stored in a String or const char*.

String node = "012"; // received dynamically

const char* node = '012'; // received dynamically

What I need is: uint16_t n = node;

The function:

begin(uint8_t _channel, uint16_t _node_address )

begin(90, n);


Solution

  • unsigned strToInt(const char *str, int base)
    {
        const char digits[] = "01234567890ABCDEF";
        unsigned result = 0;
    
        while(*str)
        {
            result *= base;
            result += strchr(digits, *str++) - digits;
        }
        return result;
    }