Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

concatenating byte arrays

 
Alessandro Brawerman
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
just a quick question.
I have 2 different byte arrays. They are of the same size.
How can I put then together in a third byte arrays? Like concatenating 2 string in a third one.
Thanks,
Alessandro.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think the API provides a method to do this, so you will have to do it by hand. It shouldn't be difficult to create a method to concatenate the two arrays. Think about it for a minute and let us know what you come up with.

Layne

p.s. Perhaps the arraycopy() method from the System class will be helpful in implementing this.
[ April 22, 2005: Message edited by: Layne Lund ]
 
Alessandro Brawerman
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The arraycopy works.
Thanks.

This is the small test I ran to check.
byte[] t = "test".getBytes();
byte[] t1 = "test".getBytes();
byte[] t2 = new byte[8];
System.arraycopy(t,0,t2,0,4);
System.arraycopy(t1,0,t2,4,4);
byte[] t3 = "testtest".getBytes();
if(Arrays.equals(t2,t3)) System.out.println("SAME");
else System.out.println("NO");
 
Stuart Gray
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could also make the final thing more general by using the length property of each array:

byte[] t2 = new byte[t.length + t1.length];
System.arraycopy(t, 0, t2, 0, t.length);
System.arraycopy(t1, 0, t2, t.length, t2.length);
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic