gpt4 book ai didi

C/C++ 如何将 int 转换回字符串(一个单词)?

转载 作者:行者123 更新时间:2023-11-30 17:14:41 24 4
gpt4 key购买 nike

在 C 中,我正在从 txt 文件中读取字符串,例如字符串“hello”,所以我有我的:

F=fopen("text.txt","r");
fscanf(F,"%s\n",string);

现在,如果我想将此字符串转换为十六进制和十进制,我可以这样做:

for (i=0; i<strlen(string); i++)
{
sprintf(st, "%02X", string[i]); //Convert to hex
strcat(hexstring, st);

sprintf(st, "%03d", string[i]); //Convert to dec
strcat(decstring, st);
}

现在,我的问题是:我想做逆运算,但是怎么做呢?这是我转换“hello”的输出

   hex-> 68656c6c6f
dec-> 104101108108111

从“68656c6c6f”或“104101108108111”我想回到“hello”,我该怎么做?

(基本上我想做这样的网站:http://string-functions.com/; 字符串到十六进制转换器,十六进制到字符串转换器,十进制到十六进制,转换器,十六进制到十进制转换器)

最佳答案

面临的挑战是要意识到您有一个十六进制的字符串和一个十进制的字符串,这意味着您有值的字符串表示形式,而不是值本身。因此,您需要将字符串表示形式转换为适当的数值,然后再转换回原始字符串。

假设您有 hex 作为两字节十六进制字符对的字符串表示形式,以下内容将从 68656c6c6f 返回原始字符串 hello :

/* convert hex string to original */
char hex2str[80] = {0};
char *p = hex2str;
int i = 0;
int itmp = 0;

while (hex[i])
{
sscanf (&hex[i], "%02x", &itmp);
sprintf (p, "%c", itmp);
p++;
i+=2;
}
*p = 0;

printf ("\n hex2str: '%s'\n\n", hex2str);

输出

$ ./bin/c2h2c < <(printf "hello\n")

hex2str: 'hello'
<小时/>

简短的工作示例

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

#define MAXS 64

int main (void) {

char hex[] = "68656c6c6f";
char hex2str[MAXS] = {0};
char *p = hex2str;
int itmp = 0;
int i = 0;

/* convert hex string to original */
while (hex[i])
{
sscanf (&hex[i], "%02x", &itmp);
sprintf (p, "%c", itmp);
p++;
i+=2;
}
*p = 0;

printf ("\n hex2str: '%s'\n\n", hex2str);

return 0;
}

输出

$ ./bin/c2h2c

hex2str: 'hello'

关于C/C++ 如何将 int 转换回字符串(一个单词)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30225158/

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