All submissions

Convert Binary String to Integer Without strtol function or Libraries

Code

#include <stdio.h>
#include <stdint.h>
#include <string.h>

uint16_t binary_to_uint(const char *str) 
{
    int i=strlen(str)-1; //pointing i to last character in the string.
    //printf("Value of i:%d\n",i);
    int factor=1;
    int ans=0;
    while(i>=0)
    {
      ans=ans+(factor*(str[i]-'0')); //updating ans value for each iteration.
      factor=factor*2; //Incrementing factor for every iteration.
      i--;
    }
    return ans;
}

int main() 
{
    char bin[20];
    scanf("%s", bin);

    printf("%u", binary_to_uint(bin));
    return 0;
}

Solving Approach

 

 

 

Loading...

Input

1010

Expected Output

10