• Post Reply Bookmark Topic Watch Topic
  • New Topic

getting a string embedded in a byte array  RSS feed

 
Paul Boucher
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all. I'm fairly new to Java but I'm a long time programmer in other languages. (which might be my problem here)

the question I have is: if there is an ASCII string embedded inside of a binary byte array, what is the easiest/correct way to get it out?

for example:

byte[] byteArray = new byte[] {0,1,2,3,4,77,121,32,83,84,82,73,78,71,13,10}// string "My String<CR><LF>" starting at byte 5

String myEmbeddedString = byteArray[5]; // I want the whole string not just the first byte.


is the correct way to just put it in a loop and get each byte one at a time?
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Take a look at the java.lang.String class. There is a constructor that does exactly what you want.

Henry
 
Kurt Van Etten
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Paul, and welcome to the Ranch!

Take a look at the API docs for the String class. The toCharArray() method will probably do what you need. If you need more control over the character encoding used, take a look at the getBytes() method.

[edit] Oops, rereading your post, I see that you're going in the opposite direction from what I thought at first. Never mind!
 
Paul Boucher
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Henry,

I must have the syntax wrong because neither of the following are legal

String str = new String( x[5]);
and
String str = new String((byte[])x[5]);
 
Paul Boucher
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
never mind I see it

public String(byte[] bytes,
int offset,
int length)

Thank you
 
Stephan van Hulst
Saloon Keeper
Posts: 7817
142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Make sure you use the US-ASCII charset.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!