I'm finishing the book C Primer Plus by Stephen Prata and I wrote as a part of the homework program to convert binary string to decimal number:
#include <stdio.h>
#include <string.h>
typedef unsigned char byte;
typedef unsigned int uint;
int strbin_to_dec(const char *);
int main(void) {
char * wbin = "01001001";
printf("%s to dziesietnie %d.\n", wbin, strbin_to_dec(wbin));
return 0;
}
int strbin_to_dec(const char * str) {
uint result = 0;
for (int i = strlen(str) - 1, j = 0; i >= 0; i--, j++) {
byte k = str[i] - '0'; // we assume ASCII coding
k <<= j;
result += k;
}
return result;
}
Questions:
- How's the efficiency of this program?
- Are byte operations faster than normal?
gcc app.c --ansi --pedantic -Wall
\$\endgroup\$str[i] - '0';
does not need "assume ASCII coding". That is valid for all encodings. \$\endgroup\$