【问题标题】:Generate a UTF-8 character from two HEX pairs从两个 HEX 对生成一个 UTF-8 字符
【发布时间】:2013-03-06 01:35:23
【问题描述】:

我正在尝试从 2 个 HEX 对生成一个 UTF-8 字符。十六进制对来自字符串。

此代码有效:

use Encode;

my $bytes = "\xC3\xA9";
print decode_utf8($bytes);

# Prints: é and is correct

此代码不起作用:

use Encode;

my $byte1 = "C3";
my $byte2 = "A9";
my $bytes = "\x$byte1\x$byte2";
print decode_utf8($bytes);

这是我要生成的字符:http://www.fileformat.info/info/unicode/char/00e9/index.htm

感谢任何提示!

【问题讨论】:

    标签: perl utf-8


    【解决方案1】:
    use Encode;
    
    my $byte1 = "C3";
    my $byte2 = "A9";
    my $bytes = chr(hex($byte1)) . chr(hex($byte2));
    print decode_utf8($bytes);
    

    【讨论】:

    • 这个答案很完美!我感谢您的帮助。 ikegami 的回答帮助我了解了十六进制值的情况。
    【解决方案2】:

    将字符串文字视为一种迷你语言。你做不到

    "\x$hex"
    

    你不能做的更多

    my $for = 'for';
    $for (1..4) { }
    

    但是有很多方法可以做你想做的事。

    my $bytes = join '', map chr hex, @bytes_hex;
    my $bytes = pack 'C*', map hex, @bytes_hex;
    my $bytes = pack '(H*)*', @bytes_hex;
    

    【讨论】:

    • 感谢您的解释。 "\xCA" 部分让我觉得它是一个字符串,因为 0xCA 没有被引用。
    【解决方案3】:

    啊,你赢了我:

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    
    use Encode;
    use utf8::all;
    
    my $byte1 = "C3";
    my $byte2 = "A9";
    my $bytes = join '', map {chr hex} $byte1, $byte2;
    
    print decode_utf8($bytes);
    

    【讨论】:

    • 也感谢您的回答。也是有效的。
    猜你喜欢
    • 2021-09-24
    • 2016-04-25
    • 2023-02-24
    • 1970-01-01
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    相关资源
    最近更新 更多