我需要将字符串的前8个字符表示为以空格分隔的十六进制数字。
例如: “这是测试!”转换为“54 68 69 73 20 69 73 20”
我使用以下代码来执行此操作。在Perl中有更好(更简单)的方法吗?
my $hex = unpack( "H16", $string );
my $hexOut = "";
for ( my $i = 0 ; $i < length($hex) ; $i += 2 )
{
$hexOut .= substr( $hex, $i, 2 ) . " ";
}
$hexOut = substr( $hexOut, 0, -1 );
答案 0 :(得分:5)
我无法抗拒提交Perl单行!
my $string = "This is a test";
print(join(' ', unpack("(A2)*", unpack( "H16", $string ))) . "\n");
答案 1 :(得分:1)
如果拆分为null,则会得到一个字节列表。然后用十六进制打印它们。
use strict;
use warnings;
my $string = shift // 'This is the test!';
my @bytes = split //, $string;
for my $i (0..7) {
printf "%02X ", ord $bytes[$i];
}
print "\n";
但是如果你真的想要字符而不是字节,那么解包。
my @chars = unpack "C0U*", $string;
for my $i (0..7) {
printf "%02X ", $chars[$i];
}
print "\n";
对于测试字符串,它是相同的
$ ./leon01.pl
54 68 69 73 20 69 73 20
54 68 69 73 20 69 73 20
但一般情况下,它不是
$ ./leon01.pl 'A Møøse once bit my sister.'
41 20 4D C3 B8 C3 B8 73
41 20 4D F8 F8 73 65 20
$ ./leon01.pl '① ② ③ ④ ⑤ ⑥ ⑦ ⑧ ⑨ ⑩'
E2 91 A0 20 E2 91 A1 20
2460 20 2461 20 2462 20 2463 20
答案 2 :(得分:0)
我会让你决定这是否更好。只是另一种方式来做到这一点。 ; - )
#! /usr/bin/perl -w
$string = "This is the test!";
$strLength = length($string);
@bytes = unpack(A2 x $strLength,unpack("H16",$string));
print "@bytes\n";
# Also could change it back to a string w/spaces:
$pretty = join(" ",@bytes);
print $pretty;
答案 3 :(得分:0)
my $string = "This is the test!";
my $hex_string = sprintf("%vx", substr($string, 0, 8));
$hex_string =~ y/./ /;
print $hex_string, "\n";
(v修饰符是printf格式的perl特定扩展,有时在5.8.x IIRC中引入。)