简体   繁体   English

将1和0的字符串转换为二进制值,然后压缩,PHP

[英]Converting string of 1s and 0s into binary value, then compress afterwards ,PHP

I have a string for example: "10001000101010001" in PHP I am compressing it with gzcompress, but it compresses ASCII equivalent.例如,我有一个字符串:PHP 中的“10001000101010001”我用 gzcompress 压缩它,但它压缩 ASCII 等价物。 I would like to compress the string as if it were binary data not it ASCII binary equivalent.我想压缩字符串,就好像它是二进制数据而不是 ASCII 二进制数据一样。

Bascially I have 2 problems:基本上我有两个问题:

  1. how to convert a list of 1s and 0s into binary如何将 1 和 0 的列表转换为二进制
  2. compress the resulting binary with gzcompress使用 gzcompress 压缩生成的二进制文件

thanks in advance.提前致谢。

Take a look at the bindec() function.看看bindec() function。

Basically you'll want something like (dry-coded, please test it yourself before blindly trusting it)基本上你会想要这样的东西(干编码,在盲目相信之前请自己测试)

function binaryStringToBytes($binaryString) {
    $output = '';
    for($i = 0; $i < strlen($binaryString); $i += 8) {
        $output .= chr(bindec(substr($binaryString, $i, 8)));
    }
    return $output;
}

to turn a string of the format you specified into a byte string, after which you can gzcompress() it at will.将您指定格式的字符串转换为字节字符串,之后您可以随意gzcompress()它。

The complementary function is something like互补的 function 类似于

function bytesToBinaryString($byteString) {
    $out = '';
    for($i = 0; $i < strlen($byteString); $i++) {
        $out .= str_pad(decbin(ord($byteString[$i])), 8, '0', STR_PAD_LEFT);
    }
    return $out;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM