#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; }
Find the end of the string to assign power to the highest bit
then start scanning right as you downshift the mask multiplier
Test Cases
Test Results
Input
1010
Expected Output
10