PHP将位数组压缩为尽可能短的字符串 [英] PHP Compress array of bits into shortest string possible
问题描述
我有一个数组,其中包含代表真值或假值的1或0值.例如
I have an array that contains values of 1 or 0 representing true or false values. e.g.
array(1,0,0,1,0,1,1,1,1);
我想将此数组压缩/编码为尽可能短的字符串,以便可以将其存储在空间受限的位置(例如cookie)中.还需要稍后能够再次对其进行解码.我该怎么办?
I want to compress/encode this array into the shortest string possible so that it can be stored within a space constrained place such as a cookie. It also need to be able to be decoded again later. How do I go about this?
ps.我正在使用PHP
ps. I am working in PHP
推荐答案
这是我的建议:
$a = array(1,0,0,1,0,1,1,1,1,1,0,0,1,0,1,1,1,1,1,0,0,1,0,1,1,1,1);
$compressed = base64_encode(implode('', array_map(function($i) {
return chr(bindec(implode('', $i)));
}, array_chunk($a, 8))));
var_dump($compressed); // string(8) "l8vlBw=="
因此,您获得了每个8个字符(实际上是二进制 0..255
),将它们转换为整数,表示为ASCII字符,将其内嵌到字符串中并转换为base64以便将其另存为字符串.
So you get each 8 characters (which in fact is a binary 0..255
), convert them to an integer, represent as an ASCII character, implode it to a string and convert to base64 to be able to save it as a string.
UPD :
相反的方法很简单:
$original = str_split(implode('', array_map(function($i) {
return decbin(ord($i));
}, str_split(base64_decode($compressed)))));
我写得怎么样了(以防万一有人有兴趣写这样的不可读且几乎无法维护的代码):
How exactly I wrote it (just in case anyone interesting how to write such unreadable and barely maintainable code):
我已经编写了 $ original = $ compressed;
,并开始逐步逆转此表达式的右侧部分:
I've written the $original = $compressed;
and started reversing the right part of this expression step by step:
- 从base64解码为二进制字符串
- 将其拆分为数组
- 将每个字符转换为其ASCII码
- 将十进制ASCII码转换为二进制
- 将所有二进制数字合并为一个
- 将长二进制字符串拆分为数组
这篇关于PHP将位数组压缩为尽可能短的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!