简体   繁体   English

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

[英]Convert Single Byte from byte array to string using UTF-8

I need to convert Each byte b from byte array to string using UTF-8 .I am able to convert entire byte array to string using UTF-8.Please help.Below is my code that have buffer which is byte array. 我需要使用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                          
}      

This Exmaple may help you 这个例子可能对您有帮助

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);
     }
}

Output 输出量

Text : This is an example 文字:这是一个例子

Text [Byte Format] : [B@187aeca 文字[位元组格式]:[B @ 187aeca

Text [Byte Format] : [B@187aeca 文字[位元组格式]:[B @ 187aeca

Text Decryted : This is an example 文字修饰:这是一个示例

Simply cast each byte to char . 只需将每个字节转换为char

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM