#include <stdio.h> /* Convert the text representation of a binary number into an integral value. */ unsigned int btou(const char *bit) { unsigned int value = 0; while ( *bit != NULL ) /* loop through all of the text representation */ { value *= 2; /* double the previous result */ value += *bit - '0'; /* add current bit (0 or 1 from '0' or '1') */ ++bit; /* go on to the next bit */ } return value; } int main ( void ) { static const char *binary[] = { "0000","0001","0010","0011","0100","0101","0110","0111", "1000","1001","1010","1011","1100","1101","1110","1111", "1010010110100101", "11011110101011011011111011101111", }; size_t i; for ( i = 0; i < sizeof binary / sizeof *binary; ++i ) { unsigned int value = btou(binary[i]); printf("btou(\"%s\") = 0x%X = %u\n", binary[i], value, value); } return 0; } /* my output btou("0000") = 0x0 = 0 btou("0001") = 0x1 = 1 btou("0010") = 0x2 = 2 btou("0011") = 0x3 = 3 btou("0100") = 0x4 = 4 btou("0101") = 0x5 = 5 btou("0110") = 0x6 = 6 btou("0111") = 0x7 = 7 btou("1000") = 0x8 = 8 btou("1001") = 0x9 = 9 btou("1010") = 0xA = 10 btou("1011") = 0xB = 11 btou("1100") = 0xC = 12 btou("1101") = 0xD = 13 btou("1110") = 0xE = 14 btou("1111") = 0xF = 15 btou("1010010110100101") = 0xA5A5 = 42405 btou("11011110101011011011111011101111") = 0xDEADBEEF = 3735928559 */ #if 0 /* of course, if you can use standard library functions, it would be simpler yet */ #include <stdlib.h> unsigned int btou(const char *bit) { return strtoul(bit, NULL, 2); } #endif