Forum Moderators: coopster
I've got a string value which represents 4 bytes (IP addresses) separated by dashes, eg:-
192-168-0-1
I need to get the HEX equiv, without the dashes and at least 2 chars per byte, eg the above example would convert to:-
C0 A8 00 01
With me so far?
I'm not sure of the best way to process this (i.e. the most efficient). In traditional programming I'd probably loop and look for the dashes, pile results into an array and then run the IntToHex function on each array value. Then if any array < 2 chars, pad it.
Is that the best way in PHP? I ask because I've seen all sorts of toys like "explode" and I wonder if I should be doing things a little differently - PHP is obviously very geared up to playing with strings (more so than C ever was).
Thanks!
TJ
I don't need the spaces btw - that was just to make the post more readable.
How does this look, any obvious gotchas?
$ip = "192-168-0-1";
$bytes = explode("-", $ip);
$hexversion = str_pad($bytes[0], 2, '0', STR_PAD_left);
$hexversion .= str_pad($bytes[1], 2, '0', STR_PAD_left);
$hexversion .= str_pad($bytes[2], 2, '0', STR_PAD_left);
$hexversion .= str_pad($bytes[3], 2, '0', STR_PAD_left);
Thanks :)
TJ