2014-06-12 77 views
1

我已將某些字符轉換爲二進制。現在我想將它們轉換回原始字符。任何人都可以告訴我該怎麼做?將二進制字符串轉換爲字符

這是我的代碼轉換爲二進制字符。

string = Integer.toBinaryString(c); 

其中c是char類型。所以,當我將char 'a'轉換爲二進制文件時,我得到了類似這樣的內容 - 1101101

+0

你是如何從字符生成二進制文件? –

+1

post some working codfe –

+0

http://stackoverflow.com/questions/833709/converting-int-to-char-in-java [1]:http://stackoverflow.com/questions/833709/converting- int-char-in-java –

回答

0

我不確定它在android中的工作原理,但是您是否試過簡單的投射?

byte b = 90; //char Z 
char c = (char) b; 
+0

我試過了,但沒有奏效。 –

3

使用Integer.parseInt(String s, int radix)有基數= 2二進制)到String轉化爲int,然後投了intchar,像這樣:

int parseInt = Integer.parseInt(your_binary_string, 2); 
char c = (char)parseInt; 
0

幸運的是,Java API提供一個將二進制字節翻譯回原始字符的相當簡單的方法。

String char = (char)Integer.parseInt(string, 2) 

該字符串是二進制代碼的一個字節(8位)。 2表示我們目前處於2位。爲此,您需要以8位部分填充上述二進制代碼塊。

但是,函數Integer.toBinaryString(C)並不總是在8塊返回這意味着你需要確保你的原始輸出是8

倍數它最終會尋找像這樣:

public String encrypt(String message) { 
    //Creates array of all the characters in the message we want to convert to binary 
    char[] characters = message.toCharArray(); 
    String returnString = ""; 
    String preProcessed = ""; 

    for(int i = 0; i < characters.length; i++) { 
     //Converts the character to a binary string 
     preProcessed = Integer.toBinaryString((int)characters[i]); 
     //Adds enough zeros to the front of the string to make it a byte(length 8 bits) 
     String zerosToAdd = ""; 
     if(preProcessed.length() < 8) { 
      for(int j = 0; j < (8 - preProcessed.length()); j++) { 
       zerosToAdd += "0"; 
      } 
     } 
     returnString += zerosToAdd + preProcessed; 
    } 

    //Returns a string with a length that is a multiple of 8 
    return returnString; 
} 

//Converts a string message containing only 1s and 0s into ASCII plaintext 
public String decrypt(String message) { 
    //Check to make sure that the message is all 1s and 0s. 
    for(int i = 0; i < message.length(); i++) { 
     if(message.charAt(i) != '1' && message.charAt(i) != '0') { 
      return null; 
     } 
    } 

    //If the message does not have a length that is a multiple of 8, we can't decrypt it 
    if(message.length() % 8 != 0) { 
     return null; 
    } 

    //Splits the string into 8 bit segments with spaces in between 
    String returnString = ""; 
    String decrypt = ""; 
    for(int i = 0; i < message.length() - 7; i += 8) { 
     decrypt += message.substring(i, i + 8) + " "; 
    } 

    //Creates a string array with bytes that represent each of the characters in the message 
    String[] bytes = decrypt.split(" "); 
    for(int i = 0; i < bytes.length; i++) { 
     /Decrypts each character and adds it to the string to get the original message 
     returnString += (char)Integer.parseInt(bytes[i], 2); 
    } 

    return returnString; 
} 
相關問題