Convert Binary String to Integer Without strtol function or Libraries

Code

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

uint16_t pow_2(uint16_t n){
    if (n==0){
        return 1;
    }
    uint16_t sum = 1;
    while(n){
        sum *= 2;
        n--;
    }
    return sum;
}

uint16_t binary_to_uint(const char *str) {
    size_t lenght = 1;
    for (; lenght <= 17; lenght++){
        if (*(str+lenght) == '\0'){
            break;
        }
    }

    uint16_t sum = 0;
    lenght--;
    for (size_t i=0; i<(lenght+1); i++){
        char bit = *(str+i);
        if (bit == '1'){
            sum += pow_2((lenght) - i);
            // printf("l:%d i:%d :%d\n",lenght, i, sum);
        }
    }
    return sum;
}

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