Thread: Decimal to Binary

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Feb 2013
    Posts
    100

    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;
    }
    Last edited by johngoodman; 02-26-2013 at 06:52 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Decimal > Binary
    By Gemini2008 in forum C Programming
    Replies: 2
    Last Post: 11-17-2008, 04:28 PM
  2. binary to decimal ! how?
    By o0o in forum C++ Programming
    Replies: 8
    Last Post: 12-23-2003, 10:31 PM
  3. binary - decimal
    By curlious in forum C++ Programming
    Replies: 5
    Last Post: 07-31-2003, 02:25 PM
  4. decimal to binary
    By kurz7 in forum C Programming
    Replies: 8
    Last Post: 07-10-2003, 12:03 AM
  5. decimal to binary, decimal to hexadecimal and vice versa
    By Unregistered in forum C++ Programming
    Replies: 9
    Last Post: 12-08-2001, 11:07 PM