Skip to content

Instantly share code, notes, and snippets.

@krysseltillada
Created January 11, 2016 18:53
Show Gist options
  • Save krysseltillada/cd9b68e1390547321d94 to your computer and use it in GitHub Desktop.
Save krysseltillada/cd9b68e1390547321d94 to your computer and use it in GitHub Desktop.
ex 3-5 (the c programming language 2 ed)
#include <stdio.h>
#include <string.h>
void copy (char to[], char from[]) {
int i = 0;
for (; (to[i] = from[i]) != '\0'; ++i );
}
char intChar (int n) {
return (n >= 0 && n <= 9) ? n + 48 : ' ';
}
void reverse (char arr[]) {
char temp[100];
int i = 0, n = 0;
for (i = strlen (arr) - 1; i >= 0; --i, ++n)
temp[n] = arr[i];
temp[n] = '\0';
copy (arr, temp);
}
void itob (int n, char str[], int b) {
int r = 0, x = 0, r2;
if (b == 16) { // hexadecimal int to char conversion
for (; n != 0; n /= 16, ++x) {
r = n % 16;
str[x] = (r < 10) ? r + 48 : r + 55;
}
} else if (b == 2) { // binary int to char conversion
for (; n != 0; n /= 2, ++x)
str[x] = (n % 2 == 0) ? '0' : '1';
} else if (b == 8) { // octal int to char conversion
for (; n != 0; ++x) {
r2 = (n / 8) * 8;
r = n - r2;
str[x] = intChar(r); // converts the int into char
n /= 8;
}
}
str[x] = '\0'; // inserting a null character to end the string
reverse(str); // reverses the string
}
int main ()
{
char str[100];
itob(670, str, 8);
printf ("%s\n", str);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment