• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How separate a byte array into two or more byte arrays?

 
harke baj
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I want to do the following:

String c = String a + String b;
byte[] ab = convert String c to byte array;

Now I want to separate byte[] ab to recover the String a and String b;

How do I do this?

Thanks,
harke
 
Henry Wong
author
Marshal
Pie
Posts: 20881
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
harke baj wrote:
Now I want to separate byte[] ab to recover the String a and String b;


Well, since the ab byte array doesn't retain any information pertaining to the size of strings a and b, there is no way to determine how many bytes goes to which string.

However, if you can obtain the info, then the easiest option is to create new byte arrays a and b, using the size info, and using System.arraycopy() method to copy the bytes.

Henry
 
Jim Hoglund
Ranch Hand
Posts: 525
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm curious as to why you need to do this. Maybe there's a
better way to address the problem. What you want is quite
straight forward using String's length() and toCharArray()
methods. What have you tried so far?

Jim...
 
Rob Spoor
Sheriff
Pie
Posts: 20492
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
harke baj wrote:I want to do the following:

String c = String a + String b;
byte[] ab = convert String c to byte array;

Now I want to separate byte[] ab to recover the String a and String b;

How do I do this?

A related question: how do you turn String c back into Strings a and b? What separates the two? If you know this, you can turn byte[] ab back into String c first, then split that one.

I will tell you this: unless you use a special separator sequence (e.g. |) you won't be able to. If a == "Hello" and b == "World", c will become "HelloWorld". If I need to split that into a and b again, I have "HelloWorld".length() different options:
- "" and "HelloWorld"
- "H" and "elloWorld"
- ...
- "HelloWorl" and "d"
- "HelloWorld" and ""
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic