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

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

// Convert binary string to uint16_t value
uint16_t binary_to_uint(const char *str) {
    uint16_t result = 0;

    for (int i = 0; str[i] != '\0'; i++) {
        result <<= 1;  // Shift left by 1
        if (str[i] == '1') {
            result |= 1;  // Add 1 if current char is '1'
        } else if (str[i] != '0') {
            // Invalid character
            return 0xFFFF;  // Optional error handling
        }
    }

    return result;
}

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

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

Why This Is Useful in Firmware?

  • Bit-level configuration input from CLI/UART often comes as strings
  • Manually converting avoids reliance on stdlib functions
  • Helps in decoding configuration commands, boot settings

Logic Summary

  • Start with result = 0
  • For each character:
    • Left-shift result
    • Add 1 if char is '1'
    • Ignore if '0', or error if anything else

       
Loading...

Input

1010

Expected Output

10