(Only C) 将特殊字符从字符串 char 转换为十六进制

(Only C) conversion special characters from string char to hexadecimal

我正在尝试使用此代码: https://www.includehelp.com/c/convert-ascii-string-to-hexadecimal-string-in-c.aspx

这段代码在我的程序上运行完美。它完美地从 utf-8 转换为十六进制字符,如 A、m、n、d、0、9。

拜托,任何人都可以告诉我或修改这个程序,当我们在字符串中有 "special characters",比如带有重音的人声 (ñ,ç,à,á,...)。 因为,当我 运行 这个程序没有像我预期的那样工作时。

我在使用原生 C 的 RHEL 7 中工作(抱歉,我不知道版本)我试图转换为十六进制的特殊字符是 UTF-8。

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

//function to convert ascii char[] to hex-string (char[])
void string2hexString(char* input, char* output)
{
    int loop;
    int i; 

    i=0;
    loop=0;

    while(input[loop] != '[=10=]')
    {
        sprintf((char*)(output+i),"%02X", input[loop]);
        loop+=1;
        i+=2;
    }
    //insert NULL at the end of the output string
    output[i++] = '[=10=]';
}

int main(){
    char ascii_str[] = "Hello world!";
    //declare output string with double size of input string
    //because each character of input string will be converted
    //in 2 bytes
    int len = strlen(ascii_str);
    char hex_str[(len*2)+1];

    //converting ascii string to hex string
    string2hexString(ascii_str, hex_str);

    printf("ascii_str: %s\n", ascii_str);
    printf("hex_str: %s\n", hex_str);

    return 0;
}

输出

ascii_str: Hello world!

hex_str: 48656C6C6F20776F726C6421

我想要像“ñáéíóúàèìòùç”这样的条目 ascii_str 并且能够在字符串上获得此十六进制代码:

letra-> á // cod.hex--> e1
letra-> é // cod.hex--> e9
letra-> í // cod.hex--> ed
letra-> ó // cod.hex--> f3
letra-> ú // cod.hex--> fa
letra-> à // cod.hex--> e0
letra-> è // cod.hex--> e8
letra-> ì // cod.hex--> ec
letra-> ò // cod.hex--> f2
letra-> ù // cod.hex--> f9
letra-> ç // cod.hex--> e7

改变这个:

sprintf((char*)(output+i), "%02X", input[loop]);

为此(解决了你的问题):

sprintf((char*)(output+i), "%02X", (unsigned char)input[loop]);

或者更好的是,对此(摆脱了多余的转换):

sprintf(output+i, "%02X", (unsigned char)input[loop]);