Convert Binary String to Integer Without strtol function or Libraries

Code

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

int strlen(const char *str){
    int str_length = 0;
    while(*str != '\0'){
        str_length++;
        str++;
    }

    return str_length;
}

uint16_t binary_to_uint(const char *str) {
    int str_length = strlen(str);
    uint16_t int_val = 0;
    int index = 0;
    while(str_length--){
        int_val += ((str[str_length] - '0') * pow(2,index));
        index++;
    }
    
    return int_val;
}

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