I have a hexadecimal value as an ASCII string in Perl:
42dc3f74212c4e74bab2
<-- This is a string, but this is also the actual hexadecimal value I need
I need to convert that to hex, and by converting I mean \\x42\\xdc\\x3f, etc.
$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.
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.
Use pack 'H*', $key
.
From perldoc -fpack
:
h A hex string (low nybble first).
H A hex string (high nybble first).
Here is some output from the 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.