Hello everyone,
I am having a bit of trouble. I am trying to read a string and convert it to binary. I finished the code, and it works, but I can't figure out how to convert binary back to string.
Here is what I have so far:
Code:
#include <stdlib.h>
#include <string.h>
int power(int, int);
char* stob(char *); // string to binary
int main() {
char str[1024];
printf("Enter some text: ");
scanf("%s", str);
printf("Binary value: %s\n", stob(str));
return 0;
}
int power(int base, int exponent) {
int p;
for (p = 1; exponent > 0; --exponent)
p = p * base;
return p;
}
char* stob(char *str) {
int i, j, len;
static char temp[8192];
char *buffer = &temp[0];
buffer[0] = '\0';
len = (strlen(str) > 1024) ? 1024 : strlen(str);
for (i = 0; i < len; i++) {
for (j = 7; j >= 0; j--) {
if (str[i] >= power(2, j)) {
strcat(buffer, "1");
str[i] -= power(2, j);
}else {
strcat(buffer, "0");
}
}
strcat(buffer, " ");
}
return buffer;
}
I just don't know how I'd write to convert that binary value back to a string. I have some ideas, but they don't seem to be right. Can anyone assist me in this?
Also, sry I didn't feel like using pow() from math.h so I wrote my own, doh.
- Stack Overflow