gpt4 book ai didi

c - C 中的无符号字符连接

转载 作者:行者123 更新时间:2023-11-30 21:00:26 25 4
gpt4 key购买 nike

我正在尝试将字符串消息转换为 C 中的十六进制值。

例如,如果我有一条类似“abc”的消息,我希望在 162636 之前收到它,等等。我的代码如下。在这段代码中,我必须执行一些连接操作来存储它们,但现在我只能存储 36 个。我如何存储它们?

unsigned char swapNibbles(char x)
{
return ( (x & 0x0F)<<4 | (x & 0xF0)>>4 );
}

void encode(char *message, char password[40]) {
unsigned char *reversedInput = malloc(strlen(message));


for (int i = 0; i < strlen(message); ++i) {
reversedInput=swapNibbles(message[i]);
}
printf("%2x TERS ",reversedInput);
//unsigned char *bitwiseMessage = (unsigned char*)message;
//printf("DÜZ %s\n",bitwiseMessage);
//printf("TERS %u\n", swapNibbles(bitwiseMessage));
}

最佳答案

编辑

我的十六进制编码解决方案:IDEOne

<小时/>

如果您希望文本进行十六进制编码,则必须分配原始消息的两倍空间:

"abc" (3 bytes) ==> "616263" (6 bytes)

所以你需要:

unsigned char *reversedInput = malloc(2*strlen(message)+1);  // +1 for the final NULL-terminator
<小时/>
#include <string.h>
#include <malloc.h>

char* HexEncode(char* txt)
{
char* hexTxt = calloc(2*strlen(txt)+1,1);
for(char* p=hexTxt; *txt; p+=2)
{
sprintf(p, "%02x", *txt++);
}
return hexTxt;
}

int main() {
char* hexText = HexEncode("Hello World");
printf("Hexed is %s\n", hexText);
free(hexText);

return 0;
}

输出

Hexed is 48656c6c6f20576f726c64

关于c - C 中的无符号字符连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41397978/

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