使用UTF-8将单字节从字节数组转换为字符串

时间:2014-12-04 04:54:33

标签: java arrays utf-8

我需要使用UTF-8将每个字节b从字节数组转换为字符串。我能够使用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                          
}      

2 个答案:

答案 0 :(得分:0)

此Exmaple可以帮助您

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

文字解密:这是一个例子

答案 1 :(得分:0)

只需将每个字节转换为char

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