how can i in c convert a very big hex number into an array of decimals?
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};
in hex : 0xa5e043e410b73a7edfbaec785282fdd2ea43ec53db24bcddbb5d2cc44598ad16
out decimal : 75027862324382759748546370052428773536833380819057116519152055470787625790742
CodePudding user response:
The basic operation is to divide the 32-digit base 256 number with 10 and get the remainder.
From the result, I notice that both the "hex" number and the result are stored with the most significant digit first. Hence the division method can be implemented as follows:
#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;
}
Applying this to the given example can be done like this:
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");
}
}
which prints the result:
00075027862324382759748546370052428773536833380819057116519152055470787625790742