V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
assad
V2EX  ›  程序员

Python3 数字 chr 后拼接成字符串和其他语言有区别?

  •  
  •   assad · 2018-04-17 11:36:27 +08:00 · 2006 次点击
    这是一个创建于 2173 天前的主题,其中的信息可能已经有所发展或是发生改变。

    items = [119,156,161,138,90,240,56,165,114,4]

    python3

        while i < strlenth:
            self.result += chr(item)
            i += 1
    

    php

        while ($i < $strlenth) {
            $this->result .= chr($item);
            $i++;
    

    结果拼出来的字符不一样,MD5 和 base64 均不一样

    第 1 条附言  ·  2018-04-17 12:10:27 +08:00
    对于 ascii 码大于 128 的,chr 出来的字符串就有区别了
    chenstack
        1
    chenstack  
       2018-04-17 12:16:05 +08:00   ❤️ 1
    要说区别可能是 python3 字符串 encode 成 bytes 后不一样,因为 encode 默认编码是 utf-8,所给的测试代码并不完整。

    python3:
    from hashlib import md5
    items = [119,156,161,138,90,240,56,165,114,4]
    strlenth = len(items)

    result = ''
    i = 0
    while i < strlenth:
    result += chr(items[i])
    i += 1
    print(md5(result.encode('latin-1')).hexdigest())


    php:
    <?php

    $items = [119,156,161,138,90,240,56,165,114,4];
    $strlenth = count($items);

    $i = 0;
    $result = '';
    while ($i < $strlenth) {
    $result .= chr($items[$i]);
    $i++;
    }
    print(md5($result));
    ?>

    结果均为 0e996abf46e4d5acadead68fbf1f877e
    assad
        2
    assad  
    OP
       2018-04-17 13:05:47 +08:00
    encode('latin-1'),真奇葩,居然是 latin-1,我试过各种编码,就是没用这个
    @chenstack
    chenstack
        3
    chenstack  
       2018-04-17 13:30:20 +08:00   ❤️ 1
    百科的介绍:Latin1 是 ISO-8859-1 的别名,有些环境下写作 Latin-1。ISO-8859-1 编码是单字节编码,向下兼容 ASCII,其编码范围是 0x00-0xFF。因为 ISO-8859-1 编码范围使用了单字节内的所有空间,在支持 ISO-8859-1 的系统中传输和存储其他任何编码的字节流都不会被抛弃。
    所以用 encode('latin-1')时所以字节会原封不动的保留,不会被转换。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3595 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 04:36 · PVG 12:36 · LAX 21:36 · JFK 00:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.