diff options
author | Michael Hunteman <michael@huntm.net> | 2023-07-04 17:03:53 -0500 |
---|---|---|
committer | Michael Hunteman <michael@huntm.net> | 2023-07-06 17:23:45 -0500 |
commit | bfce8f0d0d828209ec0bec71371ee94a7ad62d3e (patch) | |
tree | bdf49ca788ca1ca030d5b1cccfd0c9dffeb3f69f /three/conv.c |
Initial commit
Diffstat (limited to 'three/conv.c')
-rw-r--r-- | three/conv.c | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/three/conv.c b/three/conv.c new file mode 100644 index 0000000..d3e654e --- /dev/null +++ b/three/conv.c @@ -0,0 +1,65 @@ +#include <stdio.h> +#include <limits.h> + +void +reverse(char s[]) +{ + int i = 0; + while (s[i] != '\0') { + ++i; + } + --i; + char c; + for (int j = 0; j < i / 2; ++j) { + c = s[i - j]; + s[i - j] = s[j]; + s[j] = c; + } +} + +void +itoa(int n, char s[]) +{ + int i, sign; + if ((sign = n) < 0) { + n = -n - 1; + } + i = 0; + do { + s[i++] = n % 10 + '0'; + } while ((n /= 10) > 0); + if (sign < 0) { + s[i++] = '-'; + } + s[i] = '\0'; + reverse(s); +} + +void +itob(int n, char s[], int b) +{ + int i, sign; + if ((sign = n) < 0) { + n = -n; + } + i = 0; + do { + s[i++] = (n % b <= 9) ? n % b + '0' : n % b - 10 + 'a'; + } while ((n /= b) > 0); + if (sign < 0) { + s[i++] = '-'; + } + s[i] = '\0'; + reverse(s); +} + +int +main() +{ + char s[32]; + itoa(INT_MIN, s); + printf("%s\n", s); + itob(380, s, 16); + printf("%s\n", s); + return 0; +} |