in reply to Hex to Octet

I'm not sure exactly what conversion you want, but here's the most straightforward numerical way I came up with. It gives octets in big-endian order, which is backwards from what your example does.
#!/usr/bin/perl my $hexstr = "0xb400189"; # Convert to a number in machine-byte order my $num = hex $hexstr; # Convert to a number in big-endian order my $be_num = pack("N",$num); # Extract the 4 bytes my($a,$b,$c,$d) = unpack("C4",$be_num); # And print! printf "%x.%x.%x.%x\n",$a,$b,$c,$d;
That can be simplified to a one-liner:
printf "%x.%x.%x.%x\n", unpack("C4",pack("N",hex $hexstr));

Replies are listed 'Best First'.
Re: Re: Hex to Octet
by Anonymous Monk on Sep 09, 2003 at 18:17 UTC
    Thank you,
    That is what I was looking for, now if I wanted to do the reverse should I substitute unpack for pack?

    Thank again

      I built upon sgifford's code.

      #!/usr/bin/perl my $hex = "0xb400189"; # the 0x is optional since we call hex later my $octet = hex2octet($hex); print $octet, "\n"; $hex = octet2hex($octet); print $hex, "\n"; sub hex2octet { my $hex = shift; my @octet = unpack("C4", pack("N", hex $hex)); return sprintf "%x.%x.%x.%x", reverse @octet; } sub octet2hex { my $octet = shift; my @octet = map { hex } split /\./, $octet; my $hex = unpack("N", pack("C4", reverse @octet)); return sprintf "%x", $hex; }

        Excellent!

        Thanks guys