A little bit fuzzy on the exact spec. Hope this helps.
uint32_t merge_digit(uint32_t hi, uint32_t lo, uint32_t base)
{
uint32_t r = 0;
uint32_t m = 1;
while ( lo != 0 && hi != 0 ) {
uint32_t p1 = lo % base * m;
uint32_t p2 = hi % base * m;
m *= base;
if (p1 < p2) {
r += p2; hi /= base;
} else {
r += p1; lo /= base;
}
}
return r + (lo + hi) * m;
}
uint32_t sort_digit(uint32_t x, uint32_t base)
{
uint64_t b;
for ( b = base; b <= UINT32_MAX; b *= b ) {
uint32_t r = 0;
uint32_t m = 1;
while ( x != 0 ) {
r += merge_digit(x/b%b, x%b, base) * m;
m *= b*b;
x /= b*b;
}
x = r;
}
return x;
}
Edit: Alternate solution (after viewing pwasser's answer).
uint32_t sort_digit(uint32_t x, uint32_t base)
{
uint32_t result = 0;
uint32_t i;
for ( i = 1; i < base; i++ ) {
uint32_t temp;
for ( temp = x; temp != 0; temp /= base )
if (temp%base == i)
result = result * base + i;
}
return result;
}
Edit: Test.
int main(int argc, char* argv[])
{
int x = (argc >= 2) ? strtol(argv[1], (char**) 0, 0) : 7324;
printf("before (dec): %u\n", x);
printf("after (dec): %u\n", sort_digit(x, 10));
printf("before (oct): %o\n", x);
printf("after (oct): %o\n", sort_digit(x, 8));
printf("before (hex): %X\n", x);
printf("after (hex): %X\n", sort_digit(x, 16));
return 0;
}