All submissions

Convert Binary String to Integer Without strtol function or Libraries

Code

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

uint16_t binary_to_uint(const char *str) {

    uint16_t val = 0, idx = 0, str_len = 0;

    while(str[str_len] != '\0') {
        str_len++;
    }

    for (uint16_t idx = 0; idx < str_len; ++idx) {
        val = val + (1 << idx) * (str[str_len-idx-1] - '0');
    }

    return val;
}

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

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

Solving Approach

 

 

 

Loading...

Input

1010

Expected Output

10