Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Conversion from byte[] to char[]

 
Abiodun Adisa
Ranch Hand
Posts: 495
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 15272
37
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15272
37
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, credit should also go to Rob Prime who posted the same thing above!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic