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

前端 未结 5 910
时光说笑
时光说笑 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:40

    If you have a array of characters like "0x1F293C" and want to convert it to int try this code:

    char receivedByte[] = "0x1F293C";
    char *p;
    int intNumber = strtol(receivedByte, &p, 16);
    printf("The received number is: %ld.\n", intNumber);
    
    0 讨论(0)
  • 2021-01-29 08:40
    #include <stdio.h>
    
    int main(){
        char data[] = {0x1F, 0x29, 0x3C};
        int i, size = sizeof(data);
        unsigned value = 0;
    
        for(i=0;i<size;++i)
            value = value * 256 + (unsigned char)data[i];
    
        printf("0x%X %d\n", value, (int)value); 
        return 0;
    }
    
    0 讨论(0)
  • 2021-01-29 08:43
    sprintf(buffer, "%d", (((unsigned)array[0])<<16)+(((unsigned)array[1])<<8)+(unsigned)array[2];
    

    this will write the hex values in array to buffer as readable string in decimal representation.

    assuming sizeof(int)=4

    0 讨论(0)
  • 2021-01-29 08:43

    If data is declared as stated in the comments (char data[]={0x1F, 0x29, 0x3C}), you can run this program.

    #include <stdio.h>
    #include <stdlib.h>
    int main()
    {
        char receivedByte[9], *p;
        char data[] = { 0x1F, 0x29, 0x3C };
        sprintf(receivedByte, "0x%X%X%X", data[0], data[1], data[2]);
        int intNumber = strtol(receivedByte, &p, 16);
        printf("The received number is: %ld.\n", intNumber);
        return 0;
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题