converting byte[] to string

后端 未结 5 973
[愿得一人]
[愿得一人] 2021-01-13 02:51

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 g

5条回答
  •  暖寄归人
    2021-01-13 03:31

    What encoding is it? You should define it explicitly:

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

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

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

    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 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.

提交回复
热议问题