SW

[JAVA] byte 배열 합치기(System.arraycopy)

S.Zinlee 2016. 7. 22. 00:13

패킷통신을 사용하는 프로그램을 짜던 중 전송한 패킷의 무결성을 위해 CRC 값을 붙여 전송해야 할 일이 생겼다.

이 참이 바이트 배열을 합치는 방법에 대해 포스팅 해 본다.


이 때 사용되는 함수는 System.arraycopy이다.

아래 코드는 byte 배열을 받아 마지막 2 byte에 0x12, 0x34를 붙여 주는 함수이다.

1
2
3
4
5
6
7
8
9
10
11
12
  
public byte[] addPacket(byte[] origin)
{               
    byte[] packet_data = new byte[origin.length + 2];
    byte[] addPacket = {0x12, 0x34};
 
    System.arraycopy(origin, 0, packet_data, 0, origin.length);
    System.arraycopy(addPacket, 0, packet_data, origin.length, 2);
         
    return packet_data;
}