There is no need to convert the string into numbers. Just print out the string portions inserting spaces at the required positions:
const char *sha1 = "123456789ABCDEF123456789ABCDEF123456789";
printf("In: %s\n", sha1);
printf("Out: 0x");
size_t len = strlen(sha1);
size_t digits = len % 4;
if (digits == 0)
digits = 4;
const char *src = sha1;
while (*src)
{
if (src > sha1)
printf(" ");
for (size_t i = 0; i < digits; i++)
printf("%c", *src++);
digits = 4;
}
printf("\n");
If you need the output stored in a buffer use something similar:
size_t len = strlen(sha1);
char *buf = new char[len + 4 + len / 4];
const char *src = sha1;
char *dst = buf;
*dst++ = '0';
*dst++ = 'x';
size_t digits = len % 4;
if (digits == 0)
digits = 4;
while (*src)
{
if (src > sha1)
*dst++ = ' ';
for (size_t i = 0; i < digits; i++)
*dst++ = *src++;
digits = 4;
}
*dst = '\0';
printf("In: %s\nOut: %s\n", sha1, buf);
delete [] buf