help!!!!!!!!!!!

Does anyone know how to write a c program that converts binary to decimal. Please respond ASAP.


Comments

  • : Does anyone know how to write a c program that converts binary to decimal. Please respond ASAP.



    Do you mean if you have a string of character 1's and 0's and you want to convert that to decimal? If so, consider 101101 in binary which is 45 decimal. Initialize some variable to 0 which will hold the result. Now, going left to right in our character string, read in the character and add it to the result. If the next character is not the end of string, then multiply our result variable by 2 and add that next character you just checked a moment ago. If the next character is the end of string (NULL character perhaps?) then you are finished. Keep doing this until you reach the end of the string. Thus we have the following when trying to convert the character string "101101" to decimal:



    0 * 2 + 1 = 1

    1 * 2 + 0 = 2

    2 * 2 + 1 = 5

    5 * 2 + 1 = 11

    11 * 2 + 0 = 22

    22 * 2 + 1 = 45



    Next char is null so we quit and 45 is our answer. You can easily use some sort of loop to do this.



    Now, if you have an integer (or long) which just so happens to hold a value which would be represented with 1's and 0's, and you want to treat that as a binary value and "convert" it to decimal, then we have to do something different. I don't want to have to explain that one yet. I have some ideas but nothing solid just right now. Maybe I'm not thinking right (need more caffeine) but somehow the solution I seem to be leaning towards involves logarithms.



    Let me know if any of this still helps or if you really need to do it the other way.


  • : Does anyone know how to write a c program that converts binary to decimal. Please respond ASAP.

    :

    char str[MAX] = "";

    int mul_total = 1;

    getData(str);

    int len = strlen(str);

    if(str[0] == '1') total += 1;

    for(int i = 1; i < len; i++) {

    mul_total *= 2;

    total += (str[i] - 48) * mul_total;

    }








Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories