118. Convert Binary String to Integer Without strtol function or Libraries

Back To All Submissions
Previous Submission
Next Submission

Code

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

uint16_t binary_to_uint(const char *str) {
    // 3. current binary bit value = (length - 1 - index) * 2 * index+1
    
    // 1. Calculate length of string
    int length=0;
    while(str[length]!='\0'){
        length++;
    }
    int cur_val=0;
    int bit_val = 1;
    // 2. Start from end of string (LSB) & loop back
    // 2.1
    for(int j=0;j<length;j++){
        //Every loop bitvalue *2
        //Multiply LSB by bitvalue
        //Current value = prev cur val + LSB * (weight of bit)
        cur_val = cur_val + ((str[length-1-j]- '0') * bit_val);
        bit_val *= 2; //Every increase new significant bit *2
    }
    return cur_val;
}

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

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

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote