2014-12-04 43 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); 
    } 
相关问题