【问题标题】:Convert Single Byte from byte array to string using UTF-8使用 UTF-8 将单字节从字节数组转换为字符串
【发布时间】:2014-12-04 04:54:32
【问题描述】:

我需要使用 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                          
}      

【问题讨论】:

    标签: java arrays utf-8


    【解决方案1】:

    这个例子可以帮助你

    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

    Text Decryted : 这是一个例子

    【讨论】:

    • 我在网上找到的。但它没有帮助我,因为我需要使用 UTF-8 解码字节。
    【解决方案2】:

    只需将每个字节转换为char

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-07
      • 1970-01-01
      • 2010-11-03
      • 1970-01-01
      相关资源
      最近更新 更多