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

三世轮回 提交于 2019-12-02 23:06:10

问题


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: 1F, 29, and 3C.

I want to have one hex number like 0x1F293C, and convert it to a decimal number. So, I want to get “2042172” at the end.

The array could have n elements, so I need a general solution.

Thank you.


回答1:


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);



回答2:


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




回答3:


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;
}



回答4:


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.




回答5:


#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;
}


来源:https://stackoverflow.com/questions/25341676/how-to-convert-byte-array-containing-hex-values-to-decimal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!