1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <stdio.h>
#include "print_integer.h"

void print_integer(int n, int radix, char* prefix) {
    // We do not change the sign of n because -INT_MIN = INT_MAX + 1.  In other
    // words, if n == INT_MIN and we did n *= -1, n would overflow the int.

    // Deal with the sign for negative numbers.
    int sign = (n >= 0 ? 1 : -1);
    if(sign == -1) {
        fputc('-', stdout);
    }

    // Print the prefix.
    while(*prefix != '\0') {
        fputc(*(prefix++), stdout);
    }

    // Find the value of the left-most digit (e.g., 100 for a 3-digit base-10)
    int divisor = 1;
    for(; sign * (n / divisor - sign * radix) >= 0; divisor *= radix) { }

    // Print the digits left-to-right
    for(; divisor > 0; divisor /= radix) {
        char ch = '0' + sign * (n / divisor % radix);  // make it work for 0-9
        //if(ch >= 10) {
        //  ch += 'a' - '9' - 1;
        //}
        ch += (ch <= '9' ? 0 : 'a' - '9' - 1);  // make it work for a-z, too.
        fputc(ch, stdout);
    }
}
/* vim: set tabstop=2 shiftwidth=2 noexpandtab */

© Copyright 2020 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.