GeeCON Prague 2014*
The moose likes Java in General and the fly likes How separate a byte array into two or more byte arrays? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "How separate a byte array into two or more byte arrays?" Watch "How separate a byte array into two or more byte arrays?" New topic
Author

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

harke baj
Greenhorn

Joined: Feb 02, 2010
Posts: 28
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
Sheriff

Joined: Sep 28, 2004
Posts: 18876
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
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...


BEE MBA PMP SCJP-6
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

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 ""


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
GeeCON Prague 2014
 
subject: How separate a byte array into two or more byte arrays?