converting byte array to a String

L

lrantisi

What's the best and fastest way to convert a byte array to a String.
The (toString doesn't work, it gives strange characters).

I prefere a way that uses a loop that loops in the bytes of the array
and convert them to characters then append them to a string.

Thanks.
 
K

Karl Uppiano

K

Karl Uppiano

Karl Uppiano said:
lrantisi said:
What's the best and fastest way to convert a byte array to a String.
The (toString doesn't work, it gives strange characters).

I prefere a way that uses a loop that loops in the bytes of the array
and convert them to characters then append them to a string.

Thanks.

How about one of the variants of this, which allows you to specify a
character set encoding?

http://java.sun.com/javase/6/docs/api/java/lang/String.html#String(byte[], java.lang.String)

That URL was supposed to take you to this String constructor:

public String(byte[] bytes, String charsetName)
throws UnsupportedEncodingException

The charsetName tells the constructor how to interpret the bytes in the byte
array -- they could be UTF-8, ASCII, EBCDIC, or Swahili, which explains the
strange characters you get from toString, which just uses the default
encoding for your platform.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top