2014-03-18 40 views
1

我有下面的函數來加密一個字符串,我希望能夠顛倒過程的函數。我需要一個JavaScript過程來顛倒下面的過程

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值。我應該放棄嗎?這是一個徒勞的問題嗎?

+0

此代碼泄漏了很多變量。它似乎也可以逆轉。 – alex

+0

@alex:「泄漏很多變量」是什麼意思? – user3407988

+0

請參閱下面的答案。 – alex

回答

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置於變量聲明的前面,否則這些變量標識符將泄漏到包含範圍,直到它們解析爲止(通常是全局對象)。