bluetooth로 받은 byte 데이터 분석하기

앞서 client측에서 마우스 x,y데이터를 보낼때 사용했던 프로토콜을 예로 든다.

mouse x,y 데이터

여기서 0번째 바이트는 마우스 이동인 것을 알려주기 위해 0x02로 온다.
14 바이트는 x값, 58 바이트는 y값이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
BufferedInputStream in = null;

in = new BufferedInputStream(socket.getInputStream());

byte[] buffer = new byte[1024];
int bytes;
bytes = in.read(buffer);

if(buffer[0] == (byte)2){
byte[] xbuffer = new byte[4];
byte[] ybuffer = new byte[4];
for(int i = 0; i<4; i++){
xbuffer[i] = buffer[1+i];
ybuffer[i] = buffer[5+i];
}
int x = byteToInt(xbuffer, ByteOrder.LITTLE_ENDIAN);
int y = byteToInt(ybuffer, ByteOrder.LITTLE_ENDIAN);
mouseMove(x, y);
}

바이트를 int로 바꾸기 위한 함수인 byteToInt는 아래와 같이 구현한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static int byteToInt(byte[] bytes, ByteOrder order) {

ByteBuffer buff = ByteBuffer.allocate(Integer.SIZE/8);
buff.order(order);

// buff사이즈는 4인 상태임
// bytes를 put하면 position과 limit는 같은 위치가 됨.
buff.put(bytes);
// flip()가 실행 되면 position은 0에 위치 하게 됨.
buff.flip();

System.out.println("byteToInt : " + buff);

return buff.getInt(); // position위치(0)에서 부터 4바이트를 int로 변경하여 반환
}
공유하기