2015-05-31 86 views
3

我正在個人項目上工作。我想創建一個加密程序,讓您使用密鑰對字符串進行加密和解密。幾乎完成只需要最後一部分的幫助。我想將二進制字符串轉換爲文本。 假設二元結果(我想轉換成普通文本)是:如何將二進制字符串轉換爲文本?

01001000011000010110100001100001 

此轉換成文本是「哈哈」。

注意:我只使用BigIntegers,因爲幾乎我使用的每個數字對於普通Integer來說都太大了。

編輯:發現使用此驗證碼答案:

StringBuffer output = new StringBuffer(); 
for (int i = 0;i < input.length();i += 8) { 
    output.append((char) Integer.parseInt(input.substring(i, i + 8), 2)); 
} 
     System.out.println(output); 
+0

可能的重複http://stackoverflow.com/questions/4211705/binary-to-text-in-java – AshBringer

+0

@BipBip沒有幫助,因爲我正在使用BigIntegers。他們正在整合。 – fihdi

+0

@fihdi你可以參考這個問題http://stackoverflow.com/questions/5716830/convert-biginteger-to-shorter-string-in-java/5717191#5717191 – iYoung

回答

0

此代碼將做它在一個行:

String str = "01001000011000010110100001100001"; 

String decoded = Arrays.stream(str.split("(?<=\\G.{8})")) 
    .map(s -> Integer.parseInt(s, 2)) 
    .map(i -> "" + Character.valueOf((char)i.intValue())) 
    .collect(Collectors.joining("")); // "Haha" 

大概可以做出漂亮的,但我沒有」沒有IDE的便利(只是在我的手機上翻了一下)。

你會注意到BigInteger是不需要的,而且這段代碼可以處理任意長度的輸入。

相關問題