http://www.perlmonks.org?node_id=986525


in reply to String to hex

This seems pretty legible

sub str_to_hex { my $str = shift; return "0x" . substr(unpack("H*", $str), 0, 4); } print str_to_hex("COM7") . "\n"; # outputs: 0x434f

Replies are listed 'Best First'.
Re^2: String to hex
by Anonymous Monk on Aug 09, 2012 at 13:58 UTC
    It needs to produce 4 lines, not just one

      Eh. Really? OK, well, I would advise against this method, but I was determined to get it working using my original unpack version.. so here goes

      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"; }

      This outputs
      0x434f
      0x4d37
      0x003a
      0x0000