将byte []转换为字符串 [英] converting byte[] to string

查看:100
本文介绍了将byte []转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个byte []类型的bytearray,长度为17个字节,我想将其转换为字符串,并希望为另一个比较提供此字符串,但我得到的输出不是格式验证,我我使用下面的方法进行转换。我希望输出为易于验证的字符串,并提供相同的字符串进行比较。

I am having a bytearray of byte[] type having the length 17 bytes, i want to convert this to string and want to give this string for another comparison but the output i am getting is not in the format to validate, i am using the below method to convert.I want to output as string which is easy to validate and give this same string for comparison.

    byte[] byteArray = new byte[] {0,127,-1,-2,-54,123,12,110,89,0,0,0,0,0,0,0,0};
    String value = new String(byteArray);
    System.out.println(value);

输出: {nY

推荐答案

它是什么编码?您应该明确定义它:

What encoding is it? You should define it explicitly:

new String(byteArray, Charset.forName("UTF-32"));  //or whichever you use

否则结果是不可预测的(来自 String.String(byte [] ) 构造函数JavaDoc):

Otherwise the result is unpredictable (from String.String(byte[]) constructor JavaDoc):


通过使用解码指定的字节数组构造一个新的String平台的默认字符集

Constructs a new String by decoding the specified array of bytes using the platform's default charset

BTW我刚尝试过UTF-8,UTF-16和UTF-32 - 都会产生伪造的结果。长系列的 0 让我相信这实际上并不是一个文本。你从哪里得到这些数据?

BTW I have just tried it with UTF-8, UTF-16 and UTF-32 - all produce bogus results. The long series of 0 makes me believe that this isn't actually a text. Where do you get this data from?

更新:我用我机器上可用的所有字符集试过它:

UPDATE: I have tried it with all character sets available on my machine:

for (Map.Entry<String, Charset> entry : Charset.availableCharsets().entrySet())
{
    final String value = new String(byteArray, entry.getValue());
    System.out.println(entry.getKey() + ": " + value);
}

并且没有编码产生任何接近人类可读文本的内容......您的输入不是文字。

and no encoding produces anything close to human-readable text... Your input is not text.

这篇关于将byte []转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆