-
Decimal to Binary
I'm trying to pass a decimal number to a function and convert it to binary and return it and print it out in main. But it prints out 1011 and then seg faults...not sure where it's tripping up
Code:
int main(){
char* binNum = decToBin(25);
int i = 0;
while(binNum != NULL){
printf("%c", *(binNum+i));
i++;
}
}
char* decToBin(int dec){
char* output = malloc(20*sizeof(char));
int i = 0;
while(dec > 0){
if(dec % 2){
output[i] += '1';
}
else{
output[i] += '0';
}
dec /= 2;
i++;
}
return output;
}
-
One thread at a time, johngoodman...
-
Neither get responded to, I'm tempted to make another
-
binNum will never become NULL if malloc succeeded, so the while loop in your main function will run forever (or until SegFault, whichever comes first). You're also printing the binary backwards. There's a few other problems, compile with warning flags.
-
I don't see anything having to do with decimal in that code.
-
It might be your last if you do.
How To Ask Questions The Smart Way
I'm done with cleaning up your "me me me me me" reposting just to keep your thread at the top of the board.
Keep it here -> http://cboard.cprogramming.com/c-pro...l-reverse.html
This is closed
-
"main" needs to return 0
binNum needs to be freed to avoid a memory leak
binNum needs to be tested to see if decToBin failed
decToBin needs to check to see if malloc failed
output needs to be (8 * sizeof(dec)) +1 -> 8 bits per byte
output[i] = '1' or '0', it is not initialised, so += won't work
The string output needs to have a \0 put on the end of the string.
This is what you are probably after for that while loop in main
Code:
while(*(binNum+i) != '\0')
And after all that, your string is back the front (25 -> 0b10011) because the left side (msb) was calculated from the original number mod 2, where as the lsb of that number is the original number mod 2
Enjoy :)