- there's no way the data width is going to get to 50 bits. try 31 since you are using a *signed* integer insead of unsigned (in which case you can have 32). or better yet, why don't you try
unsigned long long
, so you can have 64?
- you forgot a close } on your first for statement
- you forgot to do a return 0; just before the end of main()
- avoid goto statements where possible. bad practice. try else.
- #include not include
- int main(void) or int main(int argc, char * argv[]) or int main(int argc, char * argv[], char * envp[]), but your syntax is wrong and should cause a problem.
- you should not break on 0, how are you going to display the rest of the digits?
- have to reverse the results... so you may need a string reversal function. your string.h library may have a strrev or _strrev in it. maybe. it's not a standard function. you will also need to convert those digits to chars. I suggest you use a char string.
- you should break; if number is too large to convert.
- I suggest you use #define for your number of bits NUMBITS like this: #define NUMBITS 64 or #define NUMBITS 50 and then use NUMBITS from there on as your replacement for 50. this way, if you make a mistake, you only need to change it in one place, and by the way, const or int or unsigned doesn't work for array declarations unless you are doing C++ and using the new operator.
#include
//printf(), scanf()
#include //getch()
#include //strrev();
#define NUMBITS 64
int main (void)
{
char digitchars[] = "0123456789abcdef";
char storage[NUMBITS+1];
char * pstorage = storage;
unsigned long long input, inputcopy; //64-bit unsigned integer
unsigned bitposition, result; //can't use an unsigned longlong as an index
storage[ NUMBITS ] = '\0'; //needs null terminator
printf ("Please enter a decimal number: ");
scanf ("%I64u", &input);
inputcopy = input;
for (bitposition=0; bitposition < NUMBITS; bitposition++)
{
result=input%2;
input=input/2;
storage[bitposition] = digitchars[result];
/*if (input==0) {
break;
}*/
}
if (0 != input)
{
printf ("\nThe number is too large to convert...");
//actually, you will never get here, the nbumber isn't going to get bigger than the bit width of the data type it's stored in.
}
strrev(storage);
//search for first non-leading zero
while ('0' == *pstorage) {
pstorage++;
}
if ('\0' == *pstorage) {
//we hit end of string. must be all zeros. so point to last zero.
pstorage = storage + NUMBITS - 1;
}
printf("%I64u-->%s\n", inputcopy, pstorage);
getch();
return 0;
}