sub str_to_hex { my $str = shift; my @h; for my $s (split(/(....)/, unpack("H*", $str))) { if ($s ne '') { if (length($s) < 4) { $s = ("0" x (4 - int(length($s)))) . $s; } push @h, "0x" . $s; } } push @h, "0x0000" while @h < 4; return @h; } for (str_to_hex("COM7:")) { print $_ . "\n"; }