gpt4 book ai didi

从循环复制到变量 c

转载 作者:行者123 更新时间:2023-11-30 15:55:57 24 4
gpt4 key购买 nike

我正在使用此代码来读取结果缓冲区。我的问题只是如何将显示十六进制字符的 C 值复制到一个新字符串中,我可以在 for 循环末尾打印该字符串。

for (long i=1; i<sizeof(buffer); i++)  //for all chars in string
{
unsigned char c = buffer[i];

switch (Format)
{
case 2: //hex
printf("%02x",c);
break;
case 1: //asc
printf("%c",c); // want to copy c to a varriable byte by byte
break;
} //end of switch format
}

最佳答案

如果我理解正确的话,这就是你需要的:

#include <stdio.h>
#include <string.h>

int main() {
long i;
int Format = 2;
char buffer[20] = "Test string";
char result[60] = "";
for (i=0; i<sizeof(buffer); i++) //for all chars in string
{
unsigned char c = buffer[i];
char* printf_format;
switch (Format) {
case 2: //hex
printf_format = "%02x";
break;
case 1: //asc
printf_format = "%c";
break;
} //end of switch format
sprintf(result + strlen(result), printf_format, c);
}
printf("result: %s\n", result);

}

这里result + strlen(result)是一个指向字符串末尾的指针。所以sprintf将被写到最后。请注意,您必须计算出输出字符串可以有多长,并分配足够的内存来容纳它。另请注意,循环中 i 的第一个值应为 0 而不是 1。

关于从循环复制到变量 c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11587921/

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