2016-08-15 121 views
-2

如何反轉這個函數?它從文本中創建一個80位的二進制代碼,我在互聯網上發現它,但不知道如何反轉操作並使得到的二進制代碼恢復文本。ASCII轉二進制函數

var ascii2bin = function(ascii) 
{ 
    var bin = "00000000000000000000000000000000000000000000000000000000000000000000000000000000"; 
    for (var i = 0; i < ascii.length; i++) 
    { 
     var code = ascii.charCodeAt(i); 
     bin += ('00000000' + code.toString(2)).slice(-8); 
    } 
    return bin.slice(-10 * 8).split('').reverse(); 
} 
+0

您可能正在尋找['parseInt(...,2)'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt)讀取二進制字節作爲char代碼值es,然後['String.fromCharCode'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode)將char代碼值轉換爲字符。 – apsillers

回答

0

你的函數截斷結果以信息價值的十個字符(見-10在最後一行),小於該長度的所以只輸入可以逆轉:

var bin2ascii = function(bin) { 
    return bin.reverse().join('').match(/.{8}/g).map(
     x => String.fromCharCode(parseInt(x, 2)) 
    ).join(''); 
} 

測試:

bin2ascii(ascii2bin('')); // '' 
bin2ascii(ascii2bin('foo bar')); // 'foo bar' 
bin2ascii(ascii2bin('Test 123')); // 'Test 123' 
bin2ascii(ascii2bin('This is a long string')); // 'ong string' 
+0

它非常完美,非常感謝你:) – Inder

相關問題