2014-12-04 102 views
0

我需要使用UTF-8將字節數組中的每個字節b轉換爲字符串。我可以使用UTF-8將整個字節數組轉換爲字符串。請幫助。下面是我的代碼,它有字節數組的緩衝區。使用UTF-8將單個字節從字節數組轉換爲字符串

String str = new String(buffer, "UTF-8"); 
// convert the array of bytes to characters using the default encoding.     
Log.d("es.pymasde.blueterm",str);      
// for each byte in the buffer(byte array) 
for(byte b:buffer) 
{ 
    //Here I need to convert Each Byte b to string using UTF-8       
}  

回答

0

這〔實施例可以幫助你

public class TestByte 
{  
     public static void main(String[] argv) { 
     String example = "This is an example"; 
     byte[] bytes = example.getBytes(); 
     System.out.println("Text : " + example); 
     System.out.println("Text [Byte Format] : " + bytes); 
     System.out.println("Text [Byte Format] : " + bytes.toString()); 
     String s = new String(bytes); 
     System.out.println("Text Decryted : " + s); 
    } 
} 

輸出

文本:這是一個例子

文本[字節格式]:[B @ 187aeca

文本[字節格式]:[B @ 187aeca

解密文本:這是一個示例

+0

我在網上找到它,但它沒有幫助我,因爲我需要使用UTF-8解碼字節。 – coder 2014-12-04 05:09:06

0

只需將每個字節投射到char即可。

for (byte b : buffer) { 
     // Here I need to convert Each Byte b to string using UTF-8 
     System.out.println((char) b); 
    } 
相關問題