I have done a lot with Java but I am currently trying to learn c. I am trying to make a program to convert a number from decimal to binary.
Here is what I have:
#include <stdio.h>
#define LENGTH 33
int main( int argc, char*argv[ ] )
{
unsigned int number, base, remainder, x, i;
char result[LENGTH];
puts( "Enter a decimal value, and a desired base: " );
scanf( " %u", &number );
scanf( " %u", &base );
x = number;
for( i=0; i < LENGTH; i++ )
{
remainder = x % base;
x = x/base;
result[i] = remainder;
}
printf( "%u equals %s (base-%u) \n", number, result, base );
//***result is probably backwards...
return 0;
}
And here is what I get when I run it:
Enter a decimal value, and a desired base:
5 2
5 equals (base-2)
What is the square and how to I get it to display as a string (char array)?
Last Edit: Your program might look like the following:
First, when writing the remainder, you should add the ASCII offset of the digit.
Also, you forgot to add
'\0'at the end.EDIT: When writing to a c-string, I usually initialize the string to zeros:
This way you don’t need to write the
null characterat the end , it is written for you.Thanks @mmyers for pointing out the overflow 🙂
I would declare the string to hold
LENGTH+1: