• Post Reply Bookmark Topic Watch Topic
  • New Topic

String to byte? and string to byte[]?  RSS feed

 
Gus Spain
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
i have a, what it seems, very easy problem. I have a string, let�s call it Str_wset that i need to transform into a byte[]. I tried using the Byte constructor, Byte(Str_wset) so later i would add it to the array, but i only get exceptions.
So the question is, how do i convert a string into a byte? or even better, how do i convert a string into a byte[]?

Thanks!
 
Sheldon Fernandes
Ranch Hand
Posts: 157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Gus,

Welcome to the JavaRanch.

You can get a byte[] from a String using the method getBytes() of the String class.

E.g.
String welcome = "JavaRanch";
byte[] welcomeBytes = welcome.getBytes();

See the documentation for String class for details on getBytes() and its overloaded method.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how do i convert a string into a byte?http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Byte.html
[ September 12, 2004: Message edited by: Dirk Schreckmann ]
 
Daniel Mayer
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As you can see from the different answers, it's not fully clear what you want the result to be...
 
Julian Kennedy
Ranch Hand
Posts: 823
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Gus,

Welcome to JavaRanch!

When posting here it's a good idea to state why you want to do something as well as what you're trying to do. Particularly in the Beginners forum (but certainly not just here) we often find that the best answer is not to do it that way at all but to do something completely different. As I say, it's a common situation.

Jules
[ September 13, 2004: Message edited by: Julian Kennedy ]
 
Anne Poe
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Gus,
is this question to do with a class assignment? i only ask because i have something somewhat similar to your problem for homework. just curious
 
Gus Spain
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oups, should have explained myself better...
Ok, i have this String which is in fact a SQL command i get from an interface. I have to send it to other users by using Spread, which is a group communication tool. My problem was that the function i needed had a byte[] as its argument, so that�s why i needed converting the string with the SQL command to a byte[].
Now, if i could only get the rest of the program to work properly...
In any case, thanks everybody!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!