我找到了以下用于将 int/char 转换为二进制的代码:
char* int2bin(int value, char* buffer, int bufferSize) {
char *nextChar = buffer + bufferSize-1; // location to write the least significant bit
*nextChar = 0; // add the null terminator
do {
nextChar--;
(value & 1) ? *nextChar = '1' : *nextChar = '0'; // if set set to '1' else '0'
value = value>>1;
if (nextChar == buffer)
break;
} while (value);
return nextChar;
}
我知道我可以做以下事情
binString = int2bin(inputBuff[i], binaryBuffer, 17);
fprintf (WriteTo, "%s\n", binString);
但是我现在想将刚刚进入 binString 的 char(转换的二进制位之一)存储在一个 char 数组中,我想将其传递到其他地方,但我缺乏对指针的理解,这使得这变得很困难知道如何得到它。
我尝试通过声明一个 char 数组并尝试存储该位来做到这一点:
char inputBuffStr[32];
然后...
binString = int2bin(inputBuff[i], binaryBuffer, 17);
inputBuffStr[i] = binString;
其中 i 作为分析输入的一部分逐位增加,binString 是 char* 类型。
我收到错误:“char *”类型的值无法分配给“char”类型的实体“inputBuffStr[i] = binString;”
如果有人可以解释我如何获得 binString 中存在的实际 0 或 1?我似乎无法理解如何对值进行 fprintf,但不将其输出到我的 char 数组?
最佳答案
您只需使用 strcpy
,它会复制以 \0
结尾的 C 样式字符串:
char inputBuffStr[32];
strcpy(inputBuffStr,binString);
顺便说一句:你的问题与 C++ 无关,所以我将标签更改为 C。
关于c - 如何存储 char* 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54538093/