artfoxe6#gmail.com new

PHP 字符串和字节序列互相转换 []byte<=>string

最近学习golang,发现字节数组 []byte 用的很多,但是在PHP中却很少看到,我就在想PHP中如何实现字节数组和字符串的转换,
一番试验下来发现方法还挺多的,记录一下
方法都很简单,直接看代码就行了

<?php

function test()
{
    //测试数据
    $testData = ["你好", "abc"];
    foreach ($testData as $bin) {
        $byte1 = tobyte3($bin);
        $byte2 = tobyte2($bin);
        $byte3 = tobyte1($bin);

        echo 'tobyte1: [' . implode(",", $byte1) . ']' . PHP_EOL;
        echo 'tobyte2: [' . implode(",", $byte2) . ']' . PHP_EOL;
        echo 'tobyte3: [' . implode(",", $byte3) . ']' . PHP_EOL;

        echo 'unbyte1: ' . unbyte1($byte1) . PHP_EOL;
        echo 'unbyte2: ' . unbyte2($byte2) . PHP_EOL;
        echo 'unbyte3: ' . unbyte3($byte3) . PHP_EOL;
    }
}

function tobyte1($str)
{
    return unpack("C*", $str);
}

function tobyte2($str)
{
    $res = [];
    //$len = mb_strlen($str, "8bit"); //这个方法也可以
    $len = strlen($str);
    for ($i = 0; $i < $len; $i++) {
        $res[] = ord($str[$i]);
    }
    return $res;
}

function tobyte3($str)
{
    $hex = bin2hex($str);
    $res = str_split($hex, 2);
    foreach ($res as &$re) {
        $re = hexdec($re);
    }
    unset($re);
    return $res;
}

function unbyte1($bytes)
{
    return pack("C*", ...$bytes);
}

function unbyte2($bytes)
{
    $str = "";
    foreach ($bytes as $byte) {
        $str .= chr($byte);
    }
    return $str;
}

function unbyte3($bytes)
{
    $str = "";
    foreach ($bytes as $byte) {
        $str .= dechex($byte);
    }
    return hex2bin($str);
}

//运行测试
test();

//输出结果

// tobyte1: [228,189,160,229,165,189]
// tobyte2: [228,189,160,229,165,189]
// tobyte3: [228,189,160,229,165,189]
// unbyte1: 你好
// unbyte2: 你好
// unbyte3: 你好
// tobyte1: [97,98,99]
// tobyte2: [97,98,99]
// tobyte3: [97,98,99]
// unbyte1: abc
// unbyte2: abc
// unbyte3: abc

tobyte 方法 将字符串转为字节序列 对应 golang 里面的 []byte("xxxx")
unbyte 方法将字节序列转字符串 对应 golang 里面的 string([]byte{})

上面三种方法中,我推荐使用pack和unpack的方式, 这两个函数在处理网络传输数据时功能强大,后面还要专门研究一下

posted @ 2022-03-18 15:10  codeAB  阅读(1221)  评论(0编辑  收藏  举报