Forum Moderators: coopster

Message Too Old, No Replies

Best way to explode a string of decimals?

And convert to padded HEX

         

trillianjedi

5:49 pm on Jun 17, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hmmmm... time to shout for help!

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

jatar_k

5:54 pm on Jun 17, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



same thing

explode on -
use dechex()
check for less than 2 and pad if necessary
implode using a space

trillianjedi

6:11 pm on Jun 17, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks Adam.

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

jatar_k

6:55 pm on Jun 17, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I don't think so, though I am only taking a quick look ;)

Scally_Ally

1:56 pm on Jun 19, 2006 (gmt 0)

10+ Year Member



Maybe have a look at these two functions that are rpovided with MySQL

INET_ATON() and INET_NTOA()

Which convert 4 byte IP addresses to and from a 32 bit unsigned int.

Don't know if this will help you as then you could change the int into a hex value.... maybe...

Ally