我有一个包含二进制字符串的char数组,我们称之为binString。我还有另一个有几个字符的字符数组,我们称之为asciiString。我想将每个asciiString字符转换为二进制字符串。
例如,binString将具有:“00001101”。 asciiString将是:“ba”。现在我想将b转换为二进制文件“01100010”并附加到binString。还将char'a'转换为bin并执行相同操作。如果有一个像“2”的字符,首先需要转换为int,然后转换为bin,所以“2”应该导致“00000010”。
到目前为止,这是我的代码:
char *asciiToBin(int value, int bitsCount)
{
char *output[16];
int i;
output[bitsCount - 1] = '\0';
for (i = bitsCount - 1; i >= 0; --i, value >>= 1)
{
output[i] = (value & 1) + '0';
}
return output;
}
现在,从另一个功能:
position = 8; // this is filled up to this character
char *binString[32];
len = 16;
bin16 = asciiToBin(atoi(operand), len);
for (int x = 0; x < len; x++)
{
char c = bin16[x];
binString[position + x + 1] = c;
}
有人可以帮忙吗?
谢谢,
答案 0 :(得分:0)
我的清理尝试:
int asciiToBin(int value, int bitsCount, char *output)
{
int i = bitsCount - 1;
output[i] = '\0';
for(; i >= 0; --i, value >>= 1)
output[i] = (value & 1) ? '1' : '0';
return(0);
}
我试图将其余部分归结为......但我不得不承认失败。我想更多了解这个目标会很有帮助......
int position = 8; // this is filled up to this character
char *binString[32];
int len = 16;
char bin16[len+1];
asciiToBin(atoi(operand), len, bin16);
for(int x = 0; x < len; x++)
binString[position + x + 1] = bin16[x];
答案 1 :(得分:0)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
char *asciiToBin(unsigned char value){
static char output[CHAR_BIT+1];
int i;
for(i = CHAR_BIT -1; i>= 0;--i, value >>= 1){
output[i] = "01"[value & 1];
}
return output;
}
char *convBinAndCat(char *d, const char *s){
char *out = strchr(d, '\0');
for(;*s;++s){
// unsigned char value = isdigit(*s) ? *s - '0' : *s;
unsigned char value = isdigit(*s) ? strcspn("0123456789", (char[]){ *s, '\0'}) : *s;
strcpy(out, asciiToBin(value));
out += CHAR_BIT;
}
return d;
}
int main(){
char binString[CHAR_BIT*4 + 1] = "00001101";
printf("%s\n", convBinAndCat(binString, "ba2"));//00001101011000100110000100000010
return 0;
}