Search code examples
chexdecimalavr

Convert Hexadecimal to Decimal in AVR Studio?


How can I convert a hexadecimal (unsigned char type) to decimal (int type) in AVR Studio?

Are there any built-in functions available for these?


Solution

  • On AVRs, I had problems using the traditional hex 2 int approach:

    char *z="82000001";
    uint32_t x=0;
    sscanf(z, "%8X", &x);
    

    or

    x = strtol(z, 0, 16);
    

    They simply provided the wrong output, and didn't have time to investigate why.

    So, for AVR Microcontrollers I wrote the following function, including relevant comments to make it easy to understand:

    /**
     * hex2int
     * take a hex string and convert it to a 32bit number (max 8 hex digits)
     */
    uint32_t hex2int(char *hex) {
        uint32_t val = 0;
        while (*hex) {
            // get current character then increment
            char byte = *hex++; 
            // transform hex character to the 4bit equivalent number, using the ascii table indexes
            if (byte >= '0' && byte <= '9') byte = byte - '0';
            else if (byte >= 'a' && byte <='f') byte = byte - 'a' + 10;
            else if (byte >= 'A' && byte <='F') byte = byte - 'A' + 10;    
            // shift 4 to make space for new digit, and add the 4 bits of the new digit 
            val = (val << 4) | (byte & 0xF);
        }
        return val;
    }
    

    Example:

    char *z ="82ABC1EF";
    uint32_t x = hex2int(z);
    printf("Number is [%X]\n", x);
    

    Will output: enter image description here

    EDIT: sscanf will also work on AVRs, but for big hex numbers you'll need to use "%lX", like this:

    char *z="82000001";
    uint32_t x=0;
    sscanf(z, "%lX", &x);