求助 PHP chr 的golang 实现

<?
    $input = "a";
    $md5hex = md5($input);
    $len = strlen($md5hex) / 2;
    $md5raw = "";
    for ($i = 0; $i < $len; $i++) {
        $md5raw = $md5raw.chr(hexdec(substr($md5hex, $i * 2 , 2)));
    }
    $keyMd5 = base64_encode($md5raw);
    echo $keyMd5;
func TestMD5Hash(t *testing.T) {
    input := "a"
    hasher := md5.New()
    hasher.Write([]byte(input))
    md5hex := hex.EncodeToString(hasher.Sum(nil))
    buf := bytes.NewBufferString("")
    for i := 0; i < len(md5hex); i = i + 2 {
        idx, _ := strconv.ParseInt(md5hex[i:i+2], 16, 10)
        buf.WriteString(fmt.Sprintf("%c", idx))
    }
    t.Log(base64.StdEncoding.EncodeToString(buf.Bytes()))
}

请问如何将上面的PHP算法改写成Golang的? 我改写的下面这个运算结果不一样。 上面PHP输出 DMF1ucDxtqgxw5niaXcmYQ== 下面Go输出 DMOBdcK5w4DDscK2wqgxw4PCmcOiaXcmYQ==

Update... PHP代码是第三方的,不能修改。

已邀请:

hmly

赞同来自:

对php更熟悉,让php将就go应该更容易些:

$input = "a";
$md5hex = md5($input);
$len = strlen($md5hex) / 2;
$md5raw = "";
for ($i = 0; $i < $len; $i++) {
    $md5raw .= mb_convert_encoding(chr(hexdec(substr($md5hex, $i * 2 , 2))), "UTF-8", "ASCII");
}
$keyMd5 = base64_encode($md5raw);
echo $keyMd5;  //DMOBdcK5w4DDscK2wqgxw4PCmcOiaXcmYQ==
    input := "a"
    hasher := md5.New()
    hasher.Write([]byte(input))
    md5hex := hex.EncodeToString(hasher.Sum(nil))
    buf := bytes.NewBufferString("")
    for i := 0; i < len(md5hex)/2; i++ {
        idx, _ := strconv.ParseInt(md5hex[i*2:i*2+2], 16, 10)
        buf.WriteString(fmt.Sprintf("%c", idx))
    }

    fmt.Println(base64.StdEncoding.EncodeToString(buf.Bytes()))  //DMOBdcK5w4DDscK2wqgxw4PCmcOiaXcmYQ==

heramerom

赞同来自:

找到解决方案了。原来Go字符串默认用UTF8编码。

func TestMD5Hash(t *testing.T) {
    input := "a"
    hasher := md5.New()
    hasher.Write([]byte(input))
    md5hex := hex.EncodeToString(hasher.Sum(nil))
    loop := len(md5hex) / 2
    buf := bytes.NewBufferString("")
    for i := 0; i < loop; i++ {
        idx, _ := strconv.ParseInt(md5hex[i*2:i*2+2], 16, 10)
        buf.WriteByte(byte(int8(idx)))
    }
    t.Log(base64.StdEncoding.EncodeToString(buf.Bytes()))
}

直接添加byte,不用做转换。

要回复问题请先登录注册