反向算法

时间:2014-10-12 08:29:38

标签: php algorithm mongodb

我正在使用此算法将MongoID从此处压缩为20个字符:Compress (shorten) PHP string from 24 characters to 20。 但是,我无法扭转它并找回我的24个字符。

有人可以给我一些指导。

我用过的代码:

$padded = str_repeat('0', 20 - strlen($purchase_id)) . $purchase_id;
$leastSignificant = base_convert(substr($padded, 14, 10), 32, 16); // will be 8 chars most

$middleSignificant = base_convert(substr($padded, 4, 10), 32, 16); // will be 8 chars most

$highSignificant = base_convert(substr($padded, 0, 4), 32, 16); // will be 4 chars most

// Concatenate, and make sure everything is correctly padded
$result = str_repeat('0', 4 - strlen($highSignificant)) . $highSignificant .
          str_repeat('0', 8 - strlen($middleSignificant )) . $middleSignificant .
          str_repeat('0', 8 - strlen($leastSignificant )) . $leastSignificant;

我收到错误:Warning: str_repeat(): Second argument has to be greater than or equal to 0

我得到的最小值和高显着值对我原来的MongoID是正确的。但不是中间意义重大。我得到25个字符而不是24个字符。

1 个答案:

答案 0 :(得分:0)

知道了!

// Pad with 0's to make sure you have 20 chars
$padded = str_repeat('0', 20 - strlen($purchase_id)) . $purchase_id;

$leastSignificant = base_convert(substr($padded, 12, 8), 32, 16); // will be 10 chars most
    var_dumped($leastSignificant,false);

$middleSignificant = base_convert(substr($padded, 4, 8), 32, 16); // will be 10 chars most
    var_dumped($middleSignificant,false);

$highSignificant = base_convert(substr($padded, 0, 4), 32, 16); // will be 4 chars most
    var_dumped($highSignificant,false);

// Concatenate, and make sure everything is correctly padded
$result = str_repeat('0', 4 - strlen($highSignificant)) . $highSignificant .
          str_repeat('0', 10 - strlen($middleSignificant )) . $middleSignificant .
          str_repeat('0', 10 - strlen($leastSignificant )) . $leastSignificant;