https://sintheta.nexus/blog/feed.xml

itob

2024-11-29

Exercise 3-5 from K&R, there's just something so satisfying about nailing an elegant solution in an instant...

char const DIGITS[16] = {
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    'A', 'B', 'C', 'D', 'E', 'F',
};

/* converts integer n into a base b character representation into string s
 * let's assume base 16 as max val
 */
void itob(int n, char s[], int b)
{
    int digits = 0;
    for (int i = n; i > 0; i /= b) digits++;

    s[digits--] = '\0';

    do {
        s[digits--] = DIGITS[n % b];
    } while (n /= b);
}

And yes, not super impressive, this is a simple exercise, and for nailing this to be happy about means I'm pretty darn stupid most of the time (spoiler: I am...), but hey... take the wins you have, and abuse them for motivation. Just a few more years and I might be half-decent at this?