gpt4 book ai didi

C - 将 char 或 int 转换为二进制字符串并附加到 char 数组

转载 作者:行者123 更新时间:2023-11-30 17:35:13 25 4
gpt4 key购买 nike

我有一个包含二进制字符串的字符数组,我们称之为 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;
}

有人可以帮忙吗?

谢谢

最佳答案

#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;
}

关于C - 将 char 或 int 转换为二进制字符串并附加到 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23049942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com