Convert Binary String to Integer Without strtol function or Libraries

Code

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

uint16_t binary_to_uint(const char *bin_str) {
    uint16_t result = 0;

    while (*bin_str != '\0') {
        result <<= 1;  // Shift left to make room for next bit

        if (*bin_str == '1') {
            result |= 1;  // Set the LSB if the current char is '1'
        }
        else if (*bin_str != '0') {
            // Invalid character — optional: handle error here
            return 0;
        }

        bin_str++;  // Move to next character
    }

    return result;
}

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