gpt4 book ai didi

c - 如何将已声明的 char 字符串(即 Unicode 字符)读取为十六进制 2 位值?

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

给定两个字符串,我必须读取每个 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);
}

最佳答案

此代码遍历字符串的字节,并识别“ASCII”字符(Unicode U+0000 .. U+007F),并且通常不打印它们,对于从 U+0080 向上的 Unicode 字符,打印出 < ,代表字符的一系列十六进制数字对,最后是 >最后,带有 ><中间分隔单独的 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>序列是一个不间断的空格,我不小心在代码中的英镑符号 £ 之后放置/留下了该空格。我不确定如果您复制答案中的代码是否会得到它。

关于c - 如何将已声明的 char 字符串(即 Unicode 字符)读取为十六进制 2 位值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54526129/

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