简体   繁体   English

这个算法是可逆的吗?

[英]Is this algorithm reversible?

I have this algorithm written in PHP for my project: 我有这个用PHP编写的算法用于我的项目:

<?php
$s = "abc"; //input -- string


$n = strlen($s);
$b = 0;
for ($i = 0; $i < $n; $i++)
{
$b += ord($s[$i]) * pow(31, ($n - ($i + 1)));
}


echo $b; //output -- int
?>

But now I have to reverse it to take the string from integer. 但现在我必须将其反转以从整数中取出字符串。 I tried but it failed, is there any way to reverse it? 我试过但它失败了,有没有办法扭转它?

EDIT: By "any way" I meant that it doesn't have to reverse to the original text, but only to reverse to text that gives that value. 编辑:通过“任何方式”我的意思是它不必反转原始文本,而只是反转给提供该值的文本。

no, it's not... 不,这不对...

easier example: let's assign every letter a value: a=1,b=2,c=3,d=4 etc... 更简单的例子:让我们为每个字母分配一个值:a = 1,b = 2,c = 3,d = 4等...

and here we go: you have "5" - you don't know whether it is "ad" or "bba" or "bc" etc. 我们走了:你有“5” - 你不知道它是“广告”还是“bba”或“bc”等。

IF the string can be guaranteed to only have lowercase letters on it, it can; 如果字符串可以保证只有小写字母,它可以; you'll have to figure out the maths for it (I suggest you work out in paper the algorithm, leaving the letters as variables; solve the equations and you'll see how to reverse it). 你必须弄清楚它的数学(我建议你在纸上算出算法,把字母留作变量;解决方程,你会看到如何反转它)。

If the string is arbitrary, then no; 如果字符串是任意的,则不; because you're converting each character to a base-31 representation of the number, shifting it and adding the results -- however, this addition has lots of carries, so you can't work out the original characters just from the digits (that is, the final number) of the result. 因为你将每个字符转换为数字的基数31表示,移动它并添加结果 - 但是,这个添加有很多进位,所以你不能只从数字中找出原始字符(那个是结果的最终数字。

EDIT: given your edit, then yes, it is possible. 编辑:给你的编辑,然后是的,这是可能的。 It can be a bit complicated, though -- i'll leave you to work out the maths yourself. 但它可能有点复杂 - 我会让你自己计算出数学。 Try juggling a bit with the number 31. 尝试用数字31来玩杂耍。

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

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