将一个1和0的数组转换为二进制变量

时间:2017-04-05 11:38:18

标签: php arrays

我正在用PHP编写一个应用程序,它需要获取任意长度的1和0数组并将其转换为二进制变量(存储在MySQL BINARY字段中)。我还需要一个函数来反转这个过程。

我想最终得到:

$bits = array(0,1,0,1,1,1,0,1);
$bin = bits2bin($bits);

bin2hex($bin); // returns "5D"

$bits = bin2bits($bin); // = array(0,1,0,1,1,1,0,1);

我写了以下两个功能,它们可以满足我的需求:

function bits2bin($bits) {
    $binarystring = implode($bits);
    $bytes = str_split($binarystring, 8);
    $hexstring = '';
    foreach($bytes as $byte) {
        $hexbyte = dechex(bindec($byte));
        $hexbyte = str_pad($hexbyte, 2, "0", STR_PAD_LEFT);
        $hexstring .= $hexbyte;
    }
    return $binary = pack('H*', $hexstring);
}

function bin2bits($binary) {
    $hexbytes = unpack('H*', $binary);
    $bits = array();
    foreach(str_split($hexbytes[1], 2) as $hexbyte) {
        $hexbyte = decbin(hexdec($hexbyte));
        $hexbyte = str_pad($hexbyte, 8, "0", STR_PAD_LEFT);
        foreach(str_split($hexbyte) as $bit) {
            $bits[] = $bit;
        }
    }
    return $bits;
}

数组应该可以是任意长度(例如3位,8位或10,000位),但如果使事情更容易,则可以仅限制为整个字节。

有更优雅/更有效的方法吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

function bits2bin($bits) {
    return implode(array_map(function ($v) { return chr(bindec(implode($v))); }, array_chunk($bits,8)));
} //Will return the binary string which corresponds to those bits (hopefully) you can alternatively cast them in MySQL.

function bin2bits($binary) {
       return str_split(base_convert(unpack("H*",$binary)[1],16,2));
}