Thread: Binary to decimal and reverse

  1. #1
    Registered User
    Join Date
    Feb 2013
    Posts
    100

    Binary to decimal and reverse

    I'm trying to write functions that take in a passed value and convert it. For example this function receives a char* to "25" in binary: 11001....right now it runs but it prints out 0 which is obviously wrong, it should be 25. Any pointers appreciated

    Code:
    main{
      char* str = "11001";
      int decNum = binToDec(str);
      printf("%d\n", decNum);
    }
    
    
    int binToDec(char* bin) {
        int num = *bin;
        int output = 0;
    
        for(int i=0; num > 0; i++) {
            if(num % 10 == 1) {
                output += pow(2, i);
            }
            num /= 10;
        }
        return output;
    }

  2. #2
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    Your string literal is not actually a number 11001, it is a string containing ASCII characters.

    0==0x30
    1==0x31

    Ascii Table - ASCII character codes and html, octal, hex and decimal chart conversion
    Fact - Beethoven wrote his first symphony in C

  3. #3
    young grasshopper jwroblewski44's Avatar
    Join Date
    May 2012
    Location
    Where the sidewalk ends
    Posts
    294
    Well the way you declare str and initialize it using double-quotes means that it is stored in read-only memory, and effectively is a constant that can not be manipulated. That is not the problem, however, it is when you attempt to assign the character array to num on line 9. What you will get is the ascii value of the character in the first position in the array, if you can even do that assignment.

  4. #4
    Registered User
    Join Date
    Feb 2013
    Posts
    100
    Quote Originally Posted by jwroblewski44 View Post
    Well the way you declare str and initialize it using double-quotes means that it is stored in read-only memory, and effectively is a constant that can not be manipulated. That is not the problem, however, it is when you attempt to assign the character array to num on line 9. What you will get is the ascii value of the character in the first position in the array, if you can even do that assignment.
    So what's a good/simple way to get around that?

  5. #5
    young grasshopper jwroblewski44's Avatar
    Join Date
    May 2012
    Location
    Where the sidewalk ends
    Posts
    294
    Instead of a character pointer, use an array.
    Code:
    char string[] = "11001";
    Then when you want to convert the string of characters into an integer, the function your looking for is atoi().
    Code:
    #include <stdlib.h>
    
    int num = atoi( bin );
    Edit: That will convert your string into eleven-thousand and one. Not quite the right way to convert the string of char from binary to decimal. That I will leave up to you!

    HINT: This forum has had this particular question asked before, which is confirmed by my google search.
    Last edited by jwroblewski44; 02-25-2013 at 11:39 PM.

  6. #6
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by jwroblewski44 View Post
    Instead of a character pointer, use an array.
    Code:
    char string[] = "11001";
    That makes no difference to the problem at hand whatsoever.


    Then when you want to convert the string of characters into an integer, the function your looking for is atoi().
    No it's not, that's an awful solution. It would only work for up to 10 zeros and ones, but an int would typically consist of say 32 bits. It also does not reduce the amount of work left to do by any amount. In fact it actually increases the amount of work remaining!

    The OP needs to start by learning how to iterate over the characters of a string.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  7. #7
    Registered User
    Join Date
    Dec 2012
    Posts
    45
    johngoodman, in the line 9 of your solution, you seem to think that you are taking the number of the string and writing it in the variable num as if it was a decimal number. That is wrong. You are only taking the first character (either '0' or '1'), and storing its ASCII code (48 or 49, respectively) in num.

    That is what jwroblewski44 recommends you to do with atoi().

    I would add that pow() is an overkill in your case. It works with floating point and you should stick to integers whenever possible. In this case, you should do:
    Code:
    output |= 1 << i;
    However, as iMalc said, this is an awful solution. You are passing through decimal base when there is no need at all. It is slow and, what is worse, it reduces severely the range of numbers you can work with.

    You should iterate through the string and set the bits of output according to the '1's and '0's you find. Read something about the difference between '0' and 0 (or '\0'), and read something about operators |, &, ^, <<, and >>.

  8. #8
    Registered User
    Join Date
    Feb 2013
    Posts
    100
    Now say I wanted to do a function like "char* decToBin(int dec)" and do the reverse...would i just do the same thing but in reverse?

  9. #9
    Registered User
    Join Date
    Feb 2013
    Posts
    100
    Here is what i came up with:
    Code:
    char* decToBin(int dec){
        char* output = "";
        while(dec > 0){
            if(dec % 2){
                output += '1';
            }
            else{
                output += '0';
            }
            dec /= 2;
            
        }
        return output;
    }

  10. #10
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    I guess you have already found out that this doesn't work.

    Code:
    char* output = "";
    "output" will point to a read only string (aka string literal) which is empty and you can't just add stuff to it.
    You need to either declare "output" as a big enough char array or allocate memory using malloc().

    Code:
    output += '1';
    "output" is a pointer and here you try to add the value of '1' to the memory address where it points to.

    I suggest you read about strings in C before continuing with your program.

    Bye, Andreas

  11. #11
    Registered User
    Join Date
    Feb 2013
    Posts
    100
    Why wouldn't this work? I get a seg fault

    Code:
    int main(){
      char* binNum = decToBin(25);
      int i = 0;
      while(binNum != NULL){
        printf("%c", *(binNum+i));
        i++;
      }
    }
    
    
    char* decToBin(int dec){
        char* output[20]; 
        int i = 0;
        while(dec > 0){
            if(dec % 2){
                output[i] += '1';
            }
            else{
                output[i] += '0';
            }
            dec /= 2;
            i++;
        }
        return *output;
    }

  12. #12
    young grasshopper jwroblewski44's Avatar
    Join Date
    May 2012
    Location
    Where the sidewalk ends
    Posts
    294
    Code:
    char * output[20];
    Incorrect declaration. You can either declare a character pointer, or a character array with enough space for 20 ( twenty ) characters. Refer to your documentation on proper pointer and array declarations. Also do read the link about strings in C posted above.

  13. #13
    Registered User
    Join Date
    Feb 2013
    Posts
    100
    Ok so now I'm declaring it like such: char* output = malloc(20*sizeof(char)); ... but when i pass it back to main it prints: 10011 ...which is 19 in binary, not 25...i also changed the return statement to "return output" rather than "return output*"...i should also mentions it still seg faults after it prints the wrong values haha

  14. #14
    Registered User
    Join Date
    May 2010
    Posts
    4,633
    Please post your current code along with any warning or error messages generated by your compiler, if any.

    Jim

  15. #15
    Registered User
    Join Date
    Feb 2013
    Posts
    100
    Quote Originally Posted by jimblumberg View Post
    Please post your current code along with any warning or error messages generated by your compiler, if any.

    Jim

    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;
    }
    I'm expecting 19 in binary, which is 11001
    But instead, here is what I get:
    10011įSegmentation fault (core dumped)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. char to binary and reverse
    By kraghavan in forum C++ Programming
    Replies: 6
    Last Post: 06-03-2010, 12:00 PM
  2. binary to decimal
    By juancardenas in forum C Programming
    Replies: 1
    Last Post: 02-19-2003, 02:47 PM
  3. Reverse of a Binary
    By xeneize in forum C++ Programming
    Replies: 3
    Last Post: 10-07-2002, 08:29 AM
  4. binary to decimal
    By jk81 in forum C Programming
    Replies: 1
    Last Post: 09-13-2002, 05:20 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