string to bitstring, bitstring to string source codeThis snippet submitted by Esa Karjalainen on 2011-09-05. It has been viewed 2803 times.Rating of 6.0 with 10 votes wchar_t * bitstr_to_str(wchar_t *buf){
int i=0, j=0;
int bitpos=0;
int bits[8] = { 128, 64, 32, 16, 8, 4, 2, 1 };
wchar_t * out = calloc(80, sizeof(wchar_t));
while(buf[i]){
switch (buf[i]){
case '1':
case '0':
out[j] += atoi(&buf[i])*bits[bitpos];
bitpos++;
if (8==bitpos) {
bitpos = 0;
j++;
}
break;
default:
break;
}
i++;
}
out[j+1]='\0';
return out;
}
char * str_to_bitstr(wchar_t * buf){
int i=0;
char * out = malloc(9*80*sizeof(char));
int bits[8] = { 128, 64, 32, 16, 8, 4, 2, 1 };
while(buf[i]){
int tmp = (int)buf[i];
for (int j=0; j!=8; j++) {
if (tmp-bits[j]>=0) {
out[(j)+i*9] = '1';
tmp-=bits[j];
} else {
out[j+i*9] = '0';
}
}
out[8+i*9] = ' ';
i++;
}
out[i*9] = '\0';
return out;
}
More C and C++ source code snippets Add a snippet! |