Convert binary to decimal | C Programming Example

Sdílet
Vložit
  • čas přidán 3. 07. 2021
  • An example of converting a string representation of a binary number to a decimal int in C. Source code: github.com/portfoliocourses/c.... Check out www.portfoliocourses.com to build a portfolio that will impress employers!
  • Jak na to + styl

Komentáře • 23

  • @nabihalkhateeb32
    @nabihalkhateeb32 Před 8 měsíci +1

    int binary_to_decimial(char *str) {
    int length = strlen(str);
    int sum = 0;

    for (int i = 0; i < length; i++) {
    int asciival = (int)str[i];
    int result;
    if (asciival == 49) asciival = 1;
    else if (asciival == 48) asciival = 0;
    result = asciival * pow(2,length - i - 1);
    sum += result;
    }
    return sum;
    }
    // I wrote this function instead that I want to share with you to see what you think about it. Also thank you a lot for this series. I am watching every single one of these videos. It is teaching me how to think like a programmer.

  • @mainchannel8828
    @mainchannel8828 Před 2 lety +1

    this helped big time, also since i was working with a 32 bit binary number I could pass additional variables into the function to tell it where to start and stop reading the binary letting me convert certain parts of it saving me having to mess around with masks

  • @justcurious1940
    @justcurious1940 Před 5 měsíci

    The best and most efficient way to get it done, Thanks :
    // An alternative method
    int binary_to_decimal(const char *binary){
    int length = strlen(binary);
    if(binary == NULL || length > 32) return 0;
    int decimal = 0;
    while(*binary != '\0'){
    int place_value = 1;
    for(int i = 0; i < length-1; i++){
    place_value*=2;
    }
    decimal += place_value*(*binary-'0');
    --length;
    ++binary;
    }
    return decimal;
    }

  • @cleightthejw2202
    @cleightthejw2202 Před rokem

    @Portfolio
    I tried this on a a Windows box and for some reason instead of getting the correct answer back it is giving me the full number of the bits as if they are all '1'. I tried it with '10101' and got back 32. and I used a second with '8 bits' which was like '00110100' but I got 256 back as the answer.
    You have any thought on this??
    I am truly new to actually trying C programming. I am doing what you do in your vids just to get familiar with it. And I have had those errors and warnings come up. So I'm definitely having to deal with that stuff.
    OH! and what's interesting is that math work inside the array braces [ ] and how it works on the left side where the rariable is.
    The thing that gets my curiosity is how does 1 variable do the work on both sides? ...[i] = ....[i] Especially with the +/- involved?

    • @PortfolioCourses
      @PortfolioCourses  Před rokem +1

      I'm not sure why, the original code is here, maybe this will help? github.com/portfoliocourses/c-example-code/blob/main/binary_to_decimal.c. In C when we have a variable on the left-hand side we are generally assigning a value to the variable, when we have a variable on the right-hand side we are generally using the "current value" of that variable. :-)

  • @sanighiabalantine8935
    @sanighiabalantine8935 Před rokem +1

    If I wanted to get the signed decimal value how would I go about doing that?

    • @PortfolioCourses
      @PortfolioCourses  Před rokem +1

      Great question Sanighia! 🙂 The first step would be to figure out how the binary number is stored. There are several ways that negative numbers can be stored in binary, for example by using a 'sign bit' to indicate the sign. But there is also two's complement: en.wikipedia.org/wiki/Two%27s_complement. Once you know the binary number is storing the number, you could apply the right algorithm from there. For example, this person claims this algorithm will work for two's complement, but I haven't tested it myself: stackoverflow.com/a/34153604.

  • @bushraw66
    @bushraw66 Před 7 měsíci

    why did you chose a pointer char to the string instead of using char array (the string itself) as a parameter?

  • @PhamousBoi
    @PhamousBoi Před 2 lety

    I have a question
    How can we ask user the binary number and print the output?
    I am new in C. Went through the playlist and got everything related to c Thanks.

    • @PhamousBoi
      @PhamousBoi Před 2 lety

      Figured it out. Thanks for the video.

    • @PortfolioCourses
      @PortfolioCourses  Před 2 lety +2

      OK, glad to hear you figured it out, but I'll leave this link here for the benefit of anyone that reads this question wants to know how to do it: stackoverflow.com/a/25441740

  • @EvanWelborn4
    @EvanWelborn4 Před rokem

    Really helpful video!!! can you make a video on how to add leading zeros when comparing too binary numbers from user input?

    • @PortfolioCourses
      @PortfolioCourses  Před rokem +2

      I'm glad the video was helpful! :-) That's an interesting idea for a video, maybe one day I can do that topic. Is this a question that's written down anywhere? Or can you provide some examples of input/output?

    • @EvanWelborn4
      @EvanWelborn4 Před rokem

      @@PortfolioCourses it’s basically a project where you have to convert two decimal numbers from user input and convert them to binary. I have that part down but the problem I cannot figure out is there is another part where you have to make the binary numbers equal in size. Ex 101 and 10110 would be 00101 and 10110. Then compare the hamming distance. I do not know how to put the two leading zeros in front of 101.

    • @PortfolioCourses
      @PortfolioCourses  Před rokem +1

      When you convert them to binary, how are they stored? In a string? It really all depends on how the data is stored. Because if they are stored as stings, you can take the difference of the string lengths and add that number of leading 0s to the smaller of the two strings. e..g..:
      // determined and set somewhere else in the code by your other code
      int numberOfZeros = 3;
      char smallerNumber[20] = "101";
      // shift all digits over by the number of zeros to insert
      int length = strlen(smallerNumber);
      for (int i = length; i >= 0; i--)
      {
      string[i + numberOfZeros] = string[i];
      }
      // insert the zeros at the front of the string/number
      for (int i = 0; i < numberOfZeros; i++)
      {
      string[i] = '0';
      }
      But again this assumes you're storing the numbers as strings, and that numberOfZeros contains the difference in string length between the larger/smaller of the numbers. :-)

    • @EvanWelborn4
      @EvanWelborn4 Před rokem +1

      @@PortfolioCourses Thank you so much! The numbers are command line arguments. I was storing them as int's, but is there any way to switch them to strings. If not, how would I do this from an integer standpoint?

  • @hebasm9110
    @hebasm9110 Před 2 lety

    I really thankful 💜💜💜💜💜💜

  • @WHITEWOLF-op3oo
    @WHITEWOLF-op3oo Před 8 měsíci

    int BiToDec(char *string){
    // declaring the neeeded variables

    int slen = strlen(string);
    int total = 0;
    int decval = 1;
    // a reverse for loop to calculate the decimal number
    for(int i =(slen -1); i >= 0; i--)
    {
    if (string[i] == '1')
    {
    total += decval;
    }
    decval *=2;
    }
    total /=2;
    return total;
    }
    int main(){
    //declaring the input variable and its size
    char input[25];
    //getting the input from the user
    printf("type in your Binary number: ");
    fgets(input,25,stdin);
    //assagin the function to a variable and than printing it
    int value = BiToDec(input);
    printf("%s, In decimal is %d",input,value);

    return 0;
    }
    So this is my code, for this and i don't know why but when trying to make it so that the input is from the user, it doubles the total of the number, now i fixed it by......well dividing by two, but i still wonder why does this problem come.

    • @justcurious1940
      @justcurious1940 Před 5 měsíci

      I think the problem that u are facing is from fgets(), It will append a new line character (
      ) at the end of the input, so decval*=2 will always run 1 more time, so doing something like this : decval/=2; can solve the issue, and also u can get ride off the last character in the user input to solve this issue.
      maybe adding a line like this can solve the problem : input[strlen(input)-1] = '\0'; // try and let me know.

  • @deepblackoutlaw9640
    @deepblackoutlaw9640 Před 5 měsíci

    int bin_to_dec(const char* bin) {
    size_t bin_length = strlen(bin);
    int i = 0;
    int dec = 0;
    while (bin[i] != '
    ') {
    if (bin[i] == '1') {
    dec += (int)pow(2, bin_length - (i + 1));
    }
    i++;
    }
    return dec;
    }