Two Laptop Bag
The moose likes Beginning Java and the fly likes Conversion from byte[] to char[] Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Conversion from byte[] to char[]" Watch "Conversion from byte[] to char[]" New topic

Conversion from byte[] to char[]

Abiodun Adisa
Ranch Hand

Joined: Jan 17, 2002
Posts: 495
Hello i have a byte array and i am trying to convert this to a char array, Can anyone offer suggestions please
Rob Spoor

Joined: Oct 27, 2005
Posts: 20184

What do these bytes represent? How did you get it?

I think that a String could be the intermediate way:

How To Ask Questions How To Answer Questions
Jiuxing Liu

Joined: Sep 08, 2007
Posts: 3
I think this:

Byte[] byte = new Byte[3]; // byte array
byte[0] = 1;
byte[1] = 2;
byte[2] = 3;

StringBuilder buffer = new StringBuilder();
for(int i;i < byte.length();i++){

//get char array
char[] ch = buffer.toString().toCharArray();
V Kumar

Joined: Oct 30, 2007
Posts: 1
Why not directly do

byte[] bytes = new byte[3]; // byte array
bytes[0] = 1;
bytes[1] = 2;
bytes[2] = 3;

char[] convertedChar = new char[bytes.length];
for(int i=0;i < bytes.length;i++){

Cheers<br /> <br />Vikram <br /> <br /><a href="" target="_blank" rel="nofollow"></a>
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15038

I guess that byte array contains text in a certain character encoding, and you want to make characters out of it.

Michael's solution converts the byte values to numeric strings. So if the bytes would have the values 65, 66, 67, the string would become "656667". Is that what you want?

Vikram's solution directly casts the bytes to chars. This assumes that the bytes are perhaps ASCII characters. If the bytes would contain 65, 66, 67, you would get "ABC".

If you know what character encoding the text in the bytes is in, then you can pass that to the constructor of class String to do the conversion correctly. For example:

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Jiuxing Liu

Joined: Sep 08, 2007
Posts: 3
Yes,Jesper's reply is good!

we should do that:

byte[] bytes = ...;
String str = new String(bytes); //using the platform's default charset
Char[] chars = str.toCharArray();
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15038

Well, credit should also go to Rob Prime who posted the same thing above!
I agree. Here's the link:
subject: Conversion from byte[] to char[]
It's not a secret anymore!