我需要一个JavaScript程序来反转以下过程

时间:2014-03-18 23:33:09

标签: javascript encoding

我有以下函数加密字符串,我希望有一个函数可以反转这个过程。

function encryptStr(thisString)
        {
            retString = "";
            /* Make retString a string of the 8-bit representations of 
               the ASCII values of its thisCharacters in order.
                       EXAMPLE: "abc" --> "011000010110001001100011"
                                 since the ASCII values for 'a', 'b' and 'c' 
                                 are 97=01100001, 98=01100010 and 99=01100011
                                 respectively
            */
            for (i = 0, j = thisString.length; i < j; i++) 
            { 
                bits = thisString.charCodeAt(i).toString(2);
                retString += new Array(8-bits.length+1).join('0') + bits;
            }
            /* Compress retString by taking each substring of 3, 4, ..., 9 
               consecutive 1's or 0's and it by the number of such consecutive
               thisCharacters followed by the thisCharacter. 
               EXAMPLES:
                    "10101000010111" --> "10101401031"
                    "001100011111111111111" --> "0011319151"
            */
            retString = retString.replace(/([01])\1{2,8}/g, function($0, $1) { return ($0.length + $1);});

            return retString;
        } 

我尝试制作一个功能,我可能做错了,因为它已经有50行了。我意识到需要继续进行大量的错误检查。例如,我刚刚意识到一个潜在的问题,因为JavaScript字符不会覆盖整个127个ASCII值。我应该放弃吗?这是徒劳的问题吗?

1 个答案:

答案 0 :(得分:2)

首先,找到字符串中不是01的数字。然后,以与原始函数折叠它们相反的方式展开它们。您可以再次使用String.prototype.replace()替换函数...

str.replace(/([2-9])([01])/g,
           function(all, replacementCount, bit) {
              return Array(+replacementCount + 1).join(bit);
           });

然后,只需将位流解码为String.fromCharCode()的字符。您需要将流分块为8位块,然后执行转换。我选择使用Array.prototype.reduce(),因为它非常适合这项任务。或者,您可以使用String.fromCharCode.apply(String, chunks.map(function(byte) { return parseInt(byte, 2); }))来获取生成的字符串。

像...一样的东西。

str.split(/(.{8})/g).reduce(function(str, byte) { 
                            return str + String.fromCharCode(parseInt(byte, 2)); 
                         }, "");

把它放在一起,你会得到像...这样的函数。

function decryptStr(thisString) {
    return thisString.replace(/([2-9])([01])/g,
    function (all, replacementCount, bit) {
        return Array(+replacementCount + 1).join(bit);
    }).split(/(.{8})/g).reduce(function (str, byte) {
        return str + String.fromCharCode(parseInt(byte, 2));
    }, "");
}

jsFiddle

另外,请记住将var放在变量声明的前面,否则这些变量标识符将泄漏到包含的范围,直到它们被解析(通常是全局对象)。