Sure, give me a couple mins to fix the error I found and add some comments.
Edit ok here you go:
Code:
#include <stdio.h>
#include <limits.h>
char *convert(unsigned int);
int main(void)
{
char *converted;
converted = convert (150); /* convert 150 to from base 10 to base 2 */
printf("%s\n", converted); /* Print the string */
return 0;
}
/* Returns the address of the static variable dest for use in the printf and whatnot */
char *convert(unsigned int num)
{
static char dest[33]; /* The character array that will hold the converted value.
It is static so we can pass the address freely */
int count; /* Counter to so we can go through the array */
unsigned int base = (unsigned)INT_MAX + 1; /* The higheset possible power of 2 that can be stored in an unsigned number */
/* Populate the dest array with characters, go until num is no longer greater than 1 or we run out of room in the array
* (Should happen in a 32 bit system) */
for ( count=0; count<32; count++, base /= 2)
{
if ( num >= base ) /* If the number is equal to or greater than the base then we can take one out of the number for that power */
{
dest[count] = '0' + 1; /* To represent 1 as a character we add 1 to the character value of 0 */
num -= base; /* Subtract the base from the number */
}
else
dest[count] = '0'; /* if the number wasn't greater than or equal to the base then we put 0 */
}
return dest; /* return the address of the array. WARNING: This array will be overwritten if you call convert() again */
}
Advance note: For more portability you can use the following lines instead:
Code:
static char dest[(sizeof(int) * CHAR_BIT) + 1];
/* other code */
for ( count=0; count<sizeof dest - 1; count++, base /= 2)
/* rest of function */