【问题标题】:C - convert char or int to binary string and append to char arrayC - 将 char 或 int 转换为二进制字符串并附加到 char 数组
【发布时间】:2014-05-27 19:31:52
【问题描述】:

我有一个包含二进制字符串的 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;
}

有人可以帮忙吗?

谢谢,

【问题讨论】:

  • 应该output 真的是16 个char* 的数组吗?
  • 你有什么问题?您需要什么帮助?
  • 上面的代码不起作用。我不确定是什么问题。另外我认为我不应该使用数组指针?替代品?
  • 注意:避免像 32 或 16 这样的幻数。建议len = sizeof(int)*CHAR_BIT + 1;

标签: c arrays string binary char


【解决方案1】:
#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;
}

【讨论】:

    【解决方案2】:

    我的清理尝试:

    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];
    

    【讨论】:

      猜你喜欢
      • 2016-08-13
      • 1970-01-01
      • 1970-01-01
      • 2020-07-18
      • 1970-01-01
      相关资源
      最近更新 更多