[英]Convert a hex string in ASCII to the same hex values using Perl
I have a hexadecimal value as an ASCII string in Perl: 我在Perl中有一个十六进制值作为ASCII字符串:
42dc3f74212c4e74bab2
<-- This is a string, but this is also the actual hexadecimal value I need 42dc3f74212c4e74bab2
<-这是一个字符串,但这也是我需要的实际十六进制值
I need to convert that to hex, and by converting I mean \\x42\\xdc\\x3f, etc. 我需要将其转换为十六进制,通过转换我的意思是\\ x42 \\ xdc \\ x3f等。
$auth_key = pack("h*", $key);
#It kind of works, but it gives me a low nibble, so I end up with 24 cd f3
, etc. #这很有效,但它给我带来的好处不多,所以我最终得到了
24 cd f3
等。
How can I convert this string into hexadecimal of the same values! 如何将这个字符串转换为相同值的十六进制!
I'm trying to feed this into a UDP socket if that helps. 如果有帮助,我正在尝试将其输入UDP套接字。
Use pack 'H*', $key
. 使用
pack 'H*', $key
。
From perldoc -fpack
: 从
perldoc -fpack
:
h A hex string (low nybble first).
H A hex string (high nybble first).
Here is some output from the shell: 这是shell的一些输出:
$perl -E'print pack "H*","42dc3f74212c4e74bab2"' | hd
00000000 42 dc 3f 74 21 2c 4e 74 ba b2 |B.?t!,Nt..|
0000000a
Another way: 其他方式:
use strict;
use warnings;
use 5.016;
my $str = "42dc3f74212c4e74bab2";
$str =~ s/(..)/chr(hex($1))/eg; #hex() -> convert hex string to decimal number, chr() -> convert decimal number to a character(string).
say $str;
say (pack "H*","42dc3f74212c4e74bab2");
--output:--
B??t!,Nt??
B??t!,Nt??
Round trip with hexdump: 十六进制转储往返:
$ perl -E'print "42dc3f74212c4e74bab2" =~ s/(..)/chr(hex($1))/erg' | hexdump -C
00000000 42 dc 3f 74 21 2c 4e 74 ba b2 |B.?t!,Nt..|
0000000a
pack()/unpack() are very efficient though, so they should be preferred. pack()/ unpack()效率很高,因此应该首选。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.