gpt4 book ai didi

C - 将 const char 十六进制字符串转换为 unsigned char

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

我找不到任何可用的实现,所以我使用 sccanf 编写了一个,但我有一个问题,我将 const char 转换为无符号字符“FFx16”形式,但是它会转换所有字符,但倒数第二个字符会更改它到 printf 输出上的“FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0F”(我已将调试函数留在测试中),我知道周围有 c++ 版本,但我更喜欢纯 c,所以这是我的尝试,但仍然不起作用:(

代码:

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

char* hex_to_char(const char* hex, int len) {
char *_a = malloc(len / 2);
int num = 0;
unsigned _b;
while(num < len) {
sscanf(&hex[num], "%02X", &_b);
_a[num/2] = _b;
num++;
}

return _a;
}

用法:

    const char* buf2 = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";
unsigned char start_seed[16];
int t = 0;
char* buf = hex_to_char(buf2, 32);
if(debug == 1) { printf("Start Seed : "); }
while(t < 16) {
start_seed[t] = (unsigned char)buf[t];
if(debug == 1) { printf("%02X", buf[t]); }
t++;
}
if(debug == 1) { printf("\n"); }

//输出:FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0F

最佳答案

使用num += 2而不是num++。 – Wintermute

关于C - 将 const char 十六进制字符串转换为 unsigned char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41076838/

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