Convert Binary String to Integer Without strtol function or Libraries

Code

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

uint16_t binary_to_uint(const char *str) {
    // Your logic here
    uint16_t ans = 0;
    int n = 0, one = 0;
    const char *temp = str;

    while(*temp != '\0'){
        temp++;
        n++;
    } 

    for(int i = n-1; i>= 0; i--){
        int digit = *str - '0';
        if(digit == 1) ans += pow(2,i);
        str++;
    }
    return ans;
}

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

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

1010

Expected Output

10