Hello evandb,
I know of a faster way to convert binary to integer.
Code:
int btoi(char *buf) {
int count, total, i, j, tmp;
total = 0;
count = strlen(buf);
for (i = 0; i <= count; i++) {
if (buf[count-i] == '1') {
tmp = 1;
for (j = 1; j < i; j++)
tmp *= 2;
total += tmp;
}
}
return total;
}
Code 1.1: Binary to Integer
This code will insert binary, e.g. 00000000000000000000000001111011 and convert it to 123.
If you want to convert an integer to binary you could do something like:
Code:
char* itob(int n) {
static char temp[32];
char *buf = &temp[0];
pos = 0;
for (i = 31; i >= 0; i--) {
buf[pos] = "01"[((n >> i) & 1)];
pos++;
}
buf[pos] = '\0';
return buf;
}
Code 1.2: Integer to Binary
Though these are example codes, they work quite well for me. Here is a sample of how to use them in a program:
Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
char input[255];
printf("Enter a signed integer: ");
fgets(input, sizeof(input), stdin);
n = atoi(input); // convert string to integer
printf("Binary value of %s is %s\n", input, itob(n));
return 0;
}
Example 1.1: Using itob()
Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
char input[255];
printf("Enter a binary (integer) value: ");
fgets(input, sizeof(input), stdin);
printf("Integer value of %s is %i\n", input, btoi(input));
return 0;
}
Example 1.2: Using btoi()
The code is alot smaller and more effective. I hope the helps,
-
Stack
Overflow