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

如何把 utf8 汉字转 16 进制格式

  •  
  •   cs5117155 · 2021-10-29 18:24:41 +08:00 · 1548 次点击
    这是一个创建于 881 天前的主题,其中的信息可能已经有所发展或是发生改变。
    echo Utf8ToHex("5g");
    function Utf8ToHex($str){
        $str = rawurlencode($str);
        $arr = explode('%',$str);
        $Hex = implode('',$arr);
        return $Hex;
    }
    

    我这个函数如果是汉字的情况它就是正确,如果是数字+英文,他就不行了。 比如输入5g得到 16 进制是35 67; 输入123456得到 16 进制是31 32 33 34 35 36; 网上找了几个 php 语言方法都不太好使

    6 条回复    2021-10-30 14:56:59 +08:00
    lcdtyph
        1
    lcdtyph  
       2021-10-29 18:31:14 +08:00 via iPhone
    没看懂,英文字母和数字经过几乎所有编码之后不都是一样的吗
    eason1874
        2
    eason1874  
       2021-10-29 20:03:55 +08:00
    网上例子很多啊,随手搜就有

    function hex_chars($data) {
    $hex = '';
    for ($i=0; $i<strlen($data); $i++) {
    $c = substr($data, $i, 1);
    //$hex .= '{'. hex_format(ord($c)). '}';
    $hex .= hex_format(ord($c));
    }
    return $hex;
    }

    function hex_format($o) {
    $h = strtoupper(dechex($o));
    $len = strlen($h);
    if ($len % 2 == 1)
    $h = "0$h";
    return $h;
    }

    echo hex_chars('5g') . "\n"; // 3567
    echo hex_chars('你好') . "\n"; // E4BDA0E5A5BD

    其实自己写也不难,徒手写考验知识,对着文档写就简单
    lululau
        3
    lululau  
       2021-10-29 21:25:10 +08:00
    echo 汉字 | od -An -tx1 | perl -alne 'print "@F"'
    cs5117155
        4
    cs5117155  
    OP
       2021-10-29 23:56:14 +08:00
    @eason1874 但是如果按照这个统一方法,输入 123456 ,就得不到`31 32 33 34 35 36`这样的结果了
    eason1874
        5
    eason1874  
       2021-10-30 12:10:35 +08:00
    @cs5117155 #4 额,这区别不就是加了个空格吗


    $hex .= hex_format(ord($c));

    改成
    $hex .= hex_format(ord($c)) . ' ';

    就有空格了,当然会导致最后也多一个空格,你可以截断不要最后一个字符,比如 return substr($hex, 0, -1);
    cs5117155
        6
    cs5117155  
    OP
       2021-10-30 14:56:59 +08:00
    @eason1874 可以了,之前我替换函数错了,有些尴尬
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3039 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 14:52 · PVG 22:52 · LAX 07:52 · JFK 10:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.