How to convert byte array (containing hex values) to decimal

前端 未结 5 912
时光说笑
时光说笑 2021-01-29 08:02

I am writing some code for an Atmel micro-controller. I am getting some data via Uart, and I store these hex values into an array.

Suppose the elements of the array are:

5条回答
  •  孤独总比滥情好
    2021-01-29 08:45

    If the input consists of n bytes and are stored starting from a pointer array, you can add the values up in the order you "received" them - i.e., in the order they are written in the array.

    unsigned int convertToDecimal (unsigned char *array, int n)
    {
        unsigned int result = 0;
    
        while (n--)
        {
            result <<= 8;
            result += *array;
            array++;
        }
        return result;
    }
    

    Note that your sample input contains 3 bytes and you want a "general solution for n bytes", and so you may run out of space really fast. This function will only work for 0..4 bytes. If you need more bytes, you can switch to long long (8 bytes, currently).

    For longer sequences than that you need to switch to a BigNum library.

提交回复
热议问题