Development/Java
Byte Array <-> Integer
후미카
2014. 5. 30. 14:35
integer 를 byte array 로 바꾸는 방법
ByteBuffer 클래스를 사용하면 간단하게 바꿀 수 있다.
private int byteArray2int(byte[] data) { ByteBuffer buffer = ByteBuffer.allocate(Integer.SIZE/8); //integer(4byte) 크기로 buffer 생성 buffer.order(ByteOrder.BIG_ENDIAN); //big endian 방식으로 정렬 예) 1025 = 0x00 0x00 0x04 0x01 buffer.put(data); //buffer에 byte array 데이터를 넣어준다. buffer.flip(); //put을 해주면 buffer의 position이 마지막 위치로 이동하는데 이것을 다시 0으로 되돌려준다. return buffer.getInt(); //position 위치로부터 integer 값을 가져온다. }
private byte[] int2byteArray(int data) { ByteBuffer buffer = ByteBuffer.allocate(Integer.SIZE/8); //integer(4byte) 크기로 buffer 생성 buffer.order(ByteOrder.BIG_ENDIAN); //big endian 방식으로 정렬 예) 1025 = 0x00 0x00 0x04 0x01 buffer.putInt(data); //buffer에 integer 데이터를 넣어준다. return buffer.array(); //byte array 를 가져온다. }