我如何在 c 中将一个非常大的十六进制数转换为十进制数组?

how can i in c convert a very big hex number into an array of decimal?

我如何在 c 中将一个非常大的十六进制数转换为一个小数数组?

unsigned char hexnr[32]={0xa5,0xe0,0x43,0xe4,0x10,0xb7,0x3a,0x7e,0xdf,0xba,0xec,0x78,0x52,0x82,0xfd,0xd2,0xea,0x43,0xec,0x53,0xdb,0x24,0xbc,0xdd,0xbb,0x5d,0x2c,0xc4,0x45,0x98,0xad,0x16};
                     
                    
char ResultInDecimals[]={7,5,0,2,7,8,6,2,3,2,4,3,8,2,7,5,9,7,4,8,5,4,6,3,7,0,0,5,2,4,2,8,7,7,3,5,3,6,8,3,3,3,8,0,8,1,9,0,5,7,1,1,6,5,1,9,1,5,2,0,5,5,4,7,0,7,8,7,6,2,5,7,9,0,7,4,2};

十六进制:0xa5e043e410b73a7edfbaec785282fdd2ea43ec53db24bcddbb5d2cc44598ad16

十进制:75027862324382759748546370052428773536833380819057116519152055470787625790742

基本运算是将32位的256进制数除以10求余

从结果中,我注意到“十六进制”数字和结果都以最高有效位在前存储。因此除法可以实现如下:

#include<stdio.h>
#include<string.h>

// Divide 256-base number in "hex" by 10 and return remainder
unsigned char div10(unsigned char *hex, unsigned size)
{
    unsigned rem = 0;
    for(int i = 0; i < size; i++)
    {
        unsigned n = rem * 256 + hex[i];
        hex[i] = n / 10;
        rem = n % 10;
    }
    return rem;
}

可以这样将其应用于给定的示例:

unsigned char hexnr[32]={0xa5,0xe0,0x43,0xe4,0x10,0xb7,0x3a,0x7e,0xdf,0xba,0xec,0x78,0x52,0x82,0xfd,0xd2,0xea,0x43,0xec,0x53,0xdb,0x24,0xbc,0xdd,0xbb,0x5d,0x2c,0xc4,0x45,0x98,0xad,0x16};  // Most significant digit first

unsigned char result[80]={0};  // Fixed 80 digits

char ResultInDecimals[]={7,5,0,2,7,8,6,2,3,2,4,3,8,2,7,5,9,7,4,8,5,4,6,3,7,0,0,5,2,4,2,8,7,7,3,5,3,6,8,3,3,3,8,0,8,1,9,0,5,7,1,1,6,5,1,9,1,5,2,0,5,5,4,7,0,7,8,7,6,2,5,7,9,0,7,4,2};   // Known result for comparison


int main(void)
{
    unsigned char hexzero[32] = {0};
    unsigned i = 0;
    while(memcmp(hexnr, hexzero, sizeof(hexnr)) != 0 && i < sizeof(result))
    {
        result[sizeof(result) - i - 1] = div10(hexnr, sizeof(hexnr));
        i++;
    }

    if(memcmp(hexnr, hexzero, sizeof(hexnr)) != 0)
    {
        printf("ERROR: result buffer too small\n");
    }
    else
    {
        for(unsigned j = 0; j < sizeof(result); j++)
        {
            printf("%c", result[j]+'0');
        }
        printf("\n");
    }
}

打印结果:

00075027862324382759748546370052428773536833380819057116519152055470787625790742