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) {
    // Your logic here
    uint16_t  i, reg, mask;
    // find the end of the string, bit 0
    for (i=0; (str[i] != '\0') && (str[i] != '\n'); i++) {
    }
    // bit zero is at position i-1
    i--;

    //printf("bit zero at position %d\n", i);
    reg = 0;
    mask = 1<<i;

    for (i=0; (str[i] != '\0') && (str[i] != '\n'); i++) {
        if (str[i] == '1') {
            reg = reg + mask;
        }
        mask = mask >> 1;
        //printf ("iteration: %d reg: %d\n", i, reg);

    }

    return reg;
}

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

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

Solving Approach

Find the end of the string to assign power to the highest bit

then start scanning right as you downshift  the mask multiplier

 

 

Was this helpful?
Upvote
Downvote