2011-03-27 121 views
2

我想知道是否可以輸入二進制數字並將它們翻譯迴文本。例如,我將輸入「01101000 01100101 01101100 01101100 01101111」,並將它轉換爲「hello」一詞。將二進制字符串轉換爲ASCII文本?

+3

http://stackoverflow.com/questions/4211705/binary-to-text-in-java的副本 – CoolBeans 2011-03-27 22:56:21

回答

5

只是一些邏輯更正:

這裏有

  1. 三個步驟打開二元集到一個整數
  2. 然後整成一個字符
  3. 然後串連成字符串你」 re building

幸運的是parseInt需要radix參數爲基地。因此,一旦您將字符串切成(大概)長度爲8的字符串數組,即可訪問必要的子字符串,您只需要(char)Integer.parseInt(s, 2)並連接即可。

String s2 = ""; 
char nextChar; 

for(int i = 0; i <= s.length()-8; i += 9) //this is a little tricky. we want [0, 7], [9, 16], etc (increment index by 9 if bytes are space-delimited) 
{ 
    nextChar = (char)Integer.parseInt(s.substring(i, i+8), 2); 
    s2 += nextChar; 
} 
相關問題