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

问题描述 投票:0回答:1

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

此代码在我的程序上运行完美。它将utf-8转换为完美的A,m,n,d,0、9之类的六个字符。

[请有人告诉我或修改此程序,当字符串内有“特殊字符”时,例如带有重音(ñ,ç,à,á,...)的人声。因为,当我运行该程序时,无法按预期工作。

我正在使用本机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] != '\0')
    {
        sprintf((char*)(output+i),"%02X", input[loop]);
        loop+=1;
        i+=2;
    }
    //insert NULL at the end of the output string
    output[i++] = '\0';
}

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
c special-characters
1个回答
0
投票

更改此:

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

为此(可以解决您的问题):

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

或者更好的是,它(摆脱了多余的演员):

sprintf(output+i, "%02X", (unsigned char)input[loop]);
© www.soinside.com 2019 - 2024. All rights reserved.