Following up on the comment I made:
Your code appears to "work" - in that it reads the input and produces
output. You might consider adding \n at the end of your printf
statements. What exactly isn't working for you? Consider using
8*sizeof(int)-1 rather than 31. You don't know ahead of time how big
an int is on your system.
With a tiny change your code works very nicely for me:
#include <stdio.h>
int main(int argc,char* argv[]) {
/*having issues with this in particular...*/
int number;
int newNumber;
int i;
printf("Enter a number in decimal...\n"); // <<< added a newline
scanf("%d",&number);
/* */
printf("%d in binary is: ",number);
for(i = sizeof(int)*8 - 1;i >= 0;i--) { // make sure `i` starts with the right size
newNumber = (number>>i);
if(newNumber & 1) {
printf("1");
}
else {
printf("0");
}
}
printf("\n"); // <<< print a newline
return 0;
}
When I run it:
Enter a number in decimal...
123
123 in binary is: 00000000000000000000000001111011
note - you do have to input an integer for this to work. If you need your code to be more robust to user "error" in the input, your best bet is to read the input as a string, then do some more parsing. For example:
char buffer[100];
printf("enter an integer:\n");
fgets(buffer, 100, stdin);
// now you can look for spaces, letters, anything you want to skip, in the string
// you could even use sscanf().
// scanf() is a terribly fragile function to use, especially with "free form user input".
if(sscanf(buffer, "%d", &number) == 1) {
// successfully converted number... run your code
} else {
printf("unable to convert input to a number!\n%s\n", buffer);
return 0;
}
another note re-reading your question, you said "program has to convert to a floating point number. This means you should do
float fnumber;
sscanf(buffer, "%f", &fnumber);
or
double dnumber;
sscanf(buffer, "%lf", &dnumber);
to do the conversion. But then, if you want to print as a binary, you need to cast the number from floating point to unsigned integer - a bit shifting operation is not well defined for a floating point number. So
unsigned int *intPtr, number;
intPtr = (unsigned int*) *fnumber; // this is hairy but it works
number = *intPtr;
and now use number as before - you will be able to print out the binary equivalent of the floating point number. There are people who will complain that the above is not "true to the standard". They might prefer it if you created a union:
union f2i
{
float fvalue;
unsigned int ivalue;
} Values;
Then assign the input to Values.fvalue, and use Values.ivalue to print out the binary number. It is still a hack...
scanf("%d"…)which does convert the input string to a number?\nat the end of yourprintfstatements. What exactly isn't working for you? Consider using8*sizeof(int)-1rather than31. You don't know ahead of time how big an int is on your system.