This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Byte to string Conversion

 
Santhana Lakshmi.S
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
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
Posts: 490
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

http://java.sun.com/j2se/1.5.0/docs/api/index.html
[ August 16, 2006: Message edited by: Rusty Shackleford ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic