开发者

Need help porting ruby function to php

I have this ruby function:

def WhitespaceHexEncode(str)
    result = ""
    whitespace = ""
    str.each_byte do |b|
        result << whitespace << "%02x" % b
        whitespace = " " * (rand(3) + 1)
    end
    result
end

I am trying to make the same on php, this is the code I have so far:

function WhitespaceHexEncode($str)
{
    $result = "";
    $whitespace = "";
    for($i=0;$i<strlen($str);$i++)
    {
        $result = $result.$whitespace.sprintf("%02x", $str[$i]);
        $whitespace = " ";
        for($x=0;$x<rand(0,5);$x++)
            $whitespace = $whitespace." ";
    }
    return $result;
}

But the PHP function doesn't show the same output as the ruby one, for example:

print WhitespaceHexEncode("test fsdf dgksdkljfsd sdfjksdfsl")

Output: 74   65 73 74   20 66  73   64   66  20   64 67   6b  73   64  6b 6c 6a  66   73 64   20 73 64   66 6a   6b  73   64   66 73   6c

--------------------------------------------------------------

echo WhitespaceHexEncode("test fsdf dgksdkljfsd sdfjksdfsl")

Output: 00 00  00    00   00  00 00  00  00 00   00    00 00    00 00   00  00   00     00  00  00   00 00    00   00 00 00   00   00   00  00   00

Can someone tell me what'开发者_如何学Cs wrong in the php code?


UPDATE: Fixed it using bin2hex()


The following should work as well:

<?php

function WhitespaceHexEncode($str) {

    $result = '';
    foreach (str_split($str) as $b) {
        $bytes      = $whitespace = sprintf('%02x', ord($b));
        $whitespace = str_repeat(' ', (rand(0, 5) + 1));
        $result    .= $bytes . $whitespace;
    }

    return $result;
}

echo WhitespaceHexEncode('test fsdf dgksdkljfsd sdfjksdfsl');
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜