Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Conversion from byte[] to char[]

Ranch Hand
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
Sheriff
Posts: 20665
65
What do these bytes represent? How did you get it?

I think that a String could be the intermediate way:

Jiuxing Liu
Greenhorn
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++){
buffer.append(byte[i]);
}

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

V Kumar
Greenhorn
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++){
convertedChar[i]=(char)bytes[i];
}

Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15482
43
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:

Jiuxing Liu
Greenhorn
Posts: 3

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
Posts: 15482
43
Well, credit should also go to Rob Prime who posted the same thing above!