ANDROID

String <-> byte , Hex 데이터 처리

지니 2018. 5. 9. 17:07
반응형



Java 




1. String ==> Byte 



string strTemp;


strTemp = "test01";



byte[] Temp = new byte[100];


Temp = strTemp.getBytes();    // String 변수값을 getBytes(); 해서 byte에 넣는다.


또는  System.arraycopy 함수를 이용해서 Temp 에 넣을 수도 있다.  5개의 인자를 설명하면


byte에 넣을 데이터 , 넣을데이터의 시작 지점 , byte 변수명 , byte변수명의 시작 지점 , byte변수에 넣을 값의 길이


System.arraycopy(strTemp.getBytes(), 0, Temp, 0, strTemp.getBytes().length); 






2. Byte 변수안의 값 출력하기


Log.e("출력...ㅎ", new String(Temp));  // 끝. test01 이 출력될것이다.






3. Hex ==> Byte 



음.. 표현이 좀 이상한데. 이건 변환이 아니라 그냥 넣으면 됩니다.



byte[] Temp = new byte[100];

Temp[0] = 0x00;

.

.

.

.

Temp[99] = (byte)0xff;



4. Hex Byte ==> String


Byte 안에 넣은 값이 String 일 경우 2번처럼 하면 되지만, Hex 데이터를 넣었으면 당연히 다 깨질것이다..

이럴땐, 


Log.e("출력...ㅎ"bytesToHex(Temp));  // 0x00 ......... 0xff  이런식으로 표현될것이다.


private final static char[] hexArray = "0123456789ABCDEF".toCharArray();


public static String bytesToHex(byte[] bytes) {

    char[] hexChars = new char[bytes.length * 5];

    for (int j = 0; j < bytes.length; j++) {

        int v = bytes[j] & 0xFF;

        hexChars[j * 5] = '0';

        hexChars[j * 5 + 1] = 'x';

        hexChars[j * 5 + 2] = hexArray[v >>> 4];

        hexChars[j * 5 + 3] = hexArray[v & 0x0F];

        hexChars[j * 5 + 4] = ' ';

    }

    return new String(hexChars);

}





5. Hex 변환 사이트.


http://mwultong.blogspot.com/2008/02/16-2-10-8-hex-calc.html

http://shaeod.tistory.com/228





반응형