使用perl将字符串转换为UTF-16

时间:2016-07-04 06:03:07

标签: perl converter utf-16

我需要使用Perl将我的消息字符串转换为UTF-16。

实施例 转换:

  

亲爱的用户,请输入您的密码以验证您的手机号码

进入:

  <00> 0065 0065 0061 0072 0020 0055 0073 0065 0072 002C 0020 0050 006C 0065   0061 0073 0065 0020 0065 006E 0074 0065 0072 0020 0079 006F 0075 0072   0020 0070 0061 0073 0073 0077 006F 0072 0064 0020 0074 006F 0020 0076   0065 0072 0069 0066 0079 0020 0079 006F 0075 0072 0020 006D 006F 0062   0069 006C 0065 0020 006E 006F 0020 002E

3 个答案:

答案 0 :(得分:2)

只需为输出的句柄指定输出编码:

#! /usr/bin/perl
use warnings;
use strict;

my $input = 'Dear User, Please enter your password to verify your mobile no .';
binmode *STDOUT, 'encoding(UTF-16)';
print $input;

测试:

$ 1.pl | xxd
0000000: feff 0044 0065 0061 0072 0020 0055 0073  ...D.e.a.r. .U.s
0000010: 0065 0072 002c 0020 0050 006c 0065 0061  .e.r.,. .P.l.e.a
0000020: 0073 0065 0020 0065 006e 0074 0065 0072  .s.e. .e.n.t.e.r
0000030: 0020 0079 006f 0075 0072 0020 0070 0061  . .y.o.u.r. .p.a
0000040: 0073 0073 0077 006f 0072 0064 0020 0074  .s.s.w.o.r.d. .t
0000050: 006f 0020 0076 0065 0072 0069 0066 0079  .o. .v.e.r.i.f.y
0000060: 0020 0079 006f 0075 0072 0020 006d 006f  . .y.o.u.r. .m.o
0000070: 0062 0069 006c 0065 0020 006e 006f 0020  .b.i.l.e. .n.o. 
0000080: 002e                                     ..

如果您想避开BOM(开头为feff),请指定字节顺序(UTF-16LEUTF16-BE)。

答案 1 :(得分:1)

如果这是针对Windows的,那么您将需要UTF-16LE

如果您需要将编码数据打印到输出文件,那么到目前为止,最好的方法是使用程序中的字符,并将输出句柄的编码设置为choroba has described

但是,如果出于任何其他原因需要UTF-16编码的字符串,例如命名文件或存储在剪贴板中,则需要单独进行编码

Encode模块将在这里为您提供帮助,这是一个示例程序。我已将解压缩和编码的字符串作为一系列无符号的16位值,以便您可以看到内容符合您的预期

use strict;
use warnings 'all';

use Encode qw/ encode :fallbacks /;


my $s = 'Dear User, Please enter your password to verify your mobile no.';

my $encoded = encode( 'UTF-16LE', $s, FB_CROAK);

print join ' ', map { sprintf '%04X', $_ } unpack 'S*', $encoded;

输出

0044 0065 0061 0072 0020 0055 0073 0065 0072 002C 0020 0050 006C 0065 0061 0073 0065 0020 0065 006E 0074 0065 0072 0020 0079 006F 0075 0072 0020 0070 0061 0073 0073 0077 006F 0072 0064 0020 0074 006F 0020 0076 0065 0072 0069 0066 0079 0020 0079 006F 0075 0072 0020 006D 006F 0062 0069 006C 0065 0020 006E 006F 002E

答案 2 :(得分:0)

对我来说这很有用

#! /usr/bin/perl
use warnings;
use strict;
use Encode qw(encode);

my $message = 'Dear User, Please enter your password to verify your mobile no.';
my $message_hex=unpack "H*",encode( 'utf-16be', $message );
print $message_hex ;

输出:     004400650061007200200055007300650072002c00200050006c006500610073006500200065006e00740065007200200079006f00750072002000700061007300730077006f0072006400200074006f002000760065007200690066007900200079006f007500720020006d006f00620069006c00650020006e006f002e