PHP.按字节顺序遍历字符串


PHP. Going through a string bytewise.

看过Caesar密码的Java的getBytes()函数后,我正在考虑将此功能克隆到PHP的可能性。

在Java中,函数是:

private static final SHIFT_LENGTH = 0x3;
public static String encode(String str) 
{
    str = "teststring";
    byte[] bytes = str.getBytes("UTF8");
    for (int i=0; i < bytes.length; ++i)
    {
        bytes[i] = bytes[i] + SHIFT_LENGTH;
    }
    // Base-64 encode
    return new BASE64Encoder().encode(bytes);
}

这个函数应该在字符串的每个字节上加三个,然后用base-64编码

function encode_php($str)
{
    $str = utf8_encode("teststring");
    $new_str = '';
    for ($i = 0; $i < strlen($str); $i++) {
        $new_str .= ord($str[$i])+3;
    }
    return base64_encode($new_str);
}

很明显,我在编码或如何处理PHP中的单个字节方面缺少了一些东西,但我不确定是什么。我尝试过使用dechex()和bin2hex(。有什么想法吗?

你不是说$new_str .= chr((ord($str[$i])+3)%256);