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) {
    uint16_t answer=0;
    int len = strlen(str);
    // go from r -> l (len-1) -> 0
    for(int i=len-1;i>=0;i--) {
        //printf("%d", i);
        if(str[i]=='1') {
            answer|=(1<<(len-1-i));
        }
    }
    return answer;
}

// 1 0 1 0
// i: (3-2-1-0)
// str[3]=='1'? answer|=(1<<3)

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