我如何读一个已经宣布字符字符串是Unicode字符为十六进制2位数值?

问题描述 投票:-2回答:1

给定两个字符串,我要读他们的每一个Unicode值的十六进制2位值。不顾ASCII字符。

char * str1 = "⍺";
char * str2 = "alpha is ⍺, beta is β and mu is µ";

我试图打印使用这些值:printf("<%02x>\n", str1);,但似乎价值是错误的(也(unsigned char)这样做,它似乎并没有工作)。

输出应该是这样的

<e2>
<e8><a2><2e>

这里是我完整的代码:

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

char *str1 = "⍺";
char *str2 = "alpha is ⍺, beta is β and mu is µ";
char *str3 = "β";
char *str4 = "µ";

int main(){
    printf("<%x>\n", (unsigned char) * str1);
    printf("<%x>", (unsigned char) * str1);
    printf("<%x>", (unsigned char) * str3);
    printf("<%x>\n", (unsigned char) * str4);
}
c unicode hex byte
1个回答
0
投票

此代码经过一个串的字节,并标识“ASCII”字符(Unicode的U + 0000 .. U + 007F),并且通常不打印,以及用于从U中的Unicode字符+ 0080向上,打印出一个<,该系列的十六进制数字对代表字符的,并最终在结束在中间分离单独UTF8编码的Unicode字符>,与><。如果你在一个或多个参数传递,它打印“ASCII”字符太多,但以自己的,而不是在十六进制编码。

#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>

static void dump_str(const char *s);

static bool print_ascii = false;

int main(int argc, char **argv)
{
    const char *strings[] =
    {
        "⍺",
        "alpha is ⍺, beta is β and mu is µ",
        "At -37ºC, the £ and the € fall apart",
        "嬀£Åºüÿ",
        "⍺βµ",
    };
    enum { NUM_STRINGS = sizeof(strings) / sizeof(strings[0]) };

    // Use argv - my compilation options don't allow unused parameters to a function
    if (argc > 1 && argv[argc] == NULL)
        print_ascii = true;

    for (int i = 0; i < NUM_STRINGS; i++)
        dump_str(strings[i]);
    return 0;
}

static void dump_str(const char *s)
{
    int c;
    bool printing_ascii = true;
    while ((c = (unsigned char)*s++) != '\0')
    {
        if (isascii(c))
        {
            if (!printing_ascii)
            {
                printing_ascii = true;
                putchar('>');
            }
            if (print_ascii)
                putchar(c);
        }
        else
        {
            if (printing_ascii)
            {
                printing_ascii = false;
                putchar('<');
            }
            else
            {
                if ((c & 0xC0) != 0x80)
                {
                    putchar('>');
                    putchar('<');
                }
            }
            printf("%2x", c);
        }
    }
    if (!printing_ascii)
        putchar('>');
    putchar('\n');
}

我所谓的程序utf8-97;在运行时,它给了我:

$ ./utf8-97
<e28dba>
<e28dba><ceb2><c2b5>
<c2ba><c2a3><c2a0><e282ac>
<c3a5><c2ac><e282ac><c2a3><c385><c2ba><c3bc><c3bf>
<e28dba><ceb2><c2b5>
$ ./utf8-97 1
<e28dba>
alpha is <e28dba>, beta is <ceb2> and mu is <c2b5>
At -37<c2ba>C, the <c2a3><c2a0>and the <e282ac> fall apart
<c3a5><c2ac><e282ac><c2a3><c385><c2ba><c3bc><c3bf>
<e28dba><ceb2><c2b5>
$ 

<c2a0>序列是一个非换空间,我不小心把/左代码英镑符号£之后。我不知道你会得到,如果你从答案复制代码。

© www.soinside.com 2019 - 2024. All rights reserved.