gpt4 book ai didi

c - 将输入文本中的十六进制值保存到字符串 var,反之亦然 ANSI C

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

我需要将文本的十六进制保存到字符串中:

_____________________
Input: apple

Output: 6170706c65
_____________________

char * text = "apple";
char * hextext = convertToHex(text); // -> ?! I don't know how

printf("Hextext is %s\n", hextext); // -> Hextext is 6170706c65

char * hextext = 6170706c65;
char * text = convertToText(hextext);

printf("Text is %s\n", text);

使用 Printf,使用 %hx 很容易,但我需要变量的值!

请问有人可以帮忙吗?!谢谢。

<小时/>

我的最终代码:

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

void convertToHex(char* input, char** output)
{
char* ptr;
int i;

// Allocate memory for hex string
*output = malloc(2 * strlen(input) + 1);

// Initialize pointer to start of the output buffer
ptr = *output;

// Read each char in input. Use sprintf to append the 2 char hex value.
// Finally advance the pointer 2 places in the output buffer.
for(i=0; i<strlen(input); i++)
{
sprintf(ptr, "%x", input[i]);
ptr++; ptr++;
}
}

void convertHexToString(char* input, char** output)
{
char* ptr;
int c;

// Allocate memory for hex string
*output = malloc(2 * (strlen(input)/2)%2==0 ? (strlen(input)/2) + 1 : (strlen(input)/2));

// Initialize pointer to start of the output buffer
ptr = *output;

// Read two char in input. Use sprintf to append the char value.
// Finally advance the input place in the output buffer.
for (;input[0] && input[1] && sscanf(input, "%2x", &c); input += 2)
{
sprintf(ptr, "%c", c);
ptr++;
}
}

int main(void)
{
char* text = "apple";
char* hexkey;
char* strtext;

convertToHex(text, &hexkey);

printf("Input: %s\n", text);
printf("Output: %s\n", hexkey);

convertHexToString(hexkey, &strtext);

printf("\nInput2: %s\n", hexkey);
printf("Output2: %s\n", strtext);

free(hexkey);
free(strtext);

return 0;
}

特别感谢 Erik Nedwidek 的帮助!

最佳答案

这就是我所指的:

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

void convertToHex(char* input, char** output) {
char* ptr;
int i;

// Allocate memory for hex string
*output = malloc(2 * strlen(input) + 1);
// Initialize pointer to start of the output buffer
ptr = *output;

// Read each char in input. Use sprintf to append the 2 char hex value.
// Finally advance the pointer 2 places in the output buffer.
for(i=0; i<strlen(input); i++) {
sprintf(ptr, "%x", input[i]);
ptr++; ptr++;
}
}

int main(void) {
char* text = "apple";
char* hex;
convertToHex(text, &hex);
printf("Input: %s\n", text);
printf("Output: %s\n", hex);

free(hex);

return 0;
}

输出为:

Input: apple 
Output: 6170706c65

关于c - 将输入文本中的十六进制值保存到字符串 var,反之亦然 ANSI C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20025904/

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