Meaningless Drivel is fun!
The moose likes Java in General and the fly likes Byte to string Conversion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Byte to string Conversion" Watch "Byte to string Conversion" New topic

Byte to string Conversion

Santhana Lakshmi.S
Ranch Hand

Joined: Aug 16, 2005
Posts: 82
I want to do the conversion of byte to string.
I am getting only byte not the byte array.
So i tried like this
byte b = "bytevalue";
String str = Byte.toString(b);
But the byte value is not at all converting to string.
Again i tried like this
byte[] b = new byte[1024];
for(int i=0;i<b.length;b++)
b[i] = somevalue;
String str = new String(b,0,b.length);
By using this only few bytes are changing because the actually size of the byte value i dont know.

Can anyone tell me how to conver byte to string?
Rusty Shackleford
Ranch Hand

Joined: Jan 03, 2006
Posts: 490
A byte can not hold a string, but it can hold a byte[] of char, provided you only use ascii values. A byte is signed 8 bit, which is the range -127 to 127. Decimal ascii values range from 0 to 127. Note that ascii values and char are integral types. However, a java char is not equivalent to ascii, but ascii is a proper subset of java char.

This should return a compiler error: byte b = "bytevalue";

try byte[] b = {'b','y','t','e','v','a','l','u','e'}, then use the appropriate String constructor or use Byte.parseByte() method. Also, if you want to print out b, you will need to iterate through the array, and a cast to char will be needed.

You can also take a String and get a byte using the appropriate String method or Byte constructor. The best advice when trying to convert something into another class is to check that classes API docs.
[ August 16, 2006: Message edited by: Rusty Shackleford ]

"Computer science is no more about computers than astronomy is about telescopes" - Edsger Dijkstra
I agree. Here's the link:
subject: Byte to string Conversion
It's not a secret anymore!