开发者

php covert a Hexadecimal number 273ef9 into a path 27/3e/f9

As the title reads, what it is an effeicent way to covert a Hexadecimal number such as 273ef9 into a path such as 27/3e/f9 in PHP?

updated:开发者_Go百科:: actually, I want a unsual number convert to dexadecimal and furthr convert to a path....but may be we can skip the middle step.


How about combining a str_split with implode? Might not be super efficient but very readable:

implode('/',str_split("273ef9",2));

As a side note, this will of course work well with larger hex strings and can handle partial (3,5,7 in length) hex numbers (by just printing it as a single letter after the last slash).

Edit: With what you're asking now (decimal -> hex -> path), it would look like this:

$num = 2572025;
$hex = dechex($num);
implode('/',str_split($hex,2));

Of course, you can combine it for an even shorter but less readable representation: implode('/',str_split(dechex($num),2));


The most efficient approach is to touch each character in the hex value exactly once, building up the string as you go. Because the string may have either an odd or even number of digits, you'll have to start with a check for this, outputting a single digit if it's an odd-length string. Then use a for loop to append groups of two digits, being careful with whether or not to add a slash. It will be a few lines of code.

Unless this code is being executed many millions of times, it probably isn't worth writing out this algorithm; Michael Petrov's is so readable and so nice. Go with this unless you have a real need to optimize.

By the way, to go from a decimal number to a hex string, just use dechex :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜