티스토리 뷰

Android/클래스

byte연산

이주성 2012. 11. 27. 14:46
unsigned byte처리
자바의 byte는 signed 타입이다. 즉 MAX = 2^7 -1(+127) MIN = -2^7 -1(-127)이다.. +, -를 표시하는데 1비트를 쓰고 있어서 그렇다. 문제는 unsigned byte를 다룰 필요가 있는 경우이다. 예를 들어 네트워크 통신을 할 때 1byte에 0xFF를 넣고, 읽어와야 할 경우가 있다. 이럴때는 어떻게 해야할까?? 아래 소스처럼 0xFF를 하라.. 똑같이 unsigned int는 0xFFFFFFFFL ((long) 0xFFFFFFFF)를 하라
public class UnsignedByte {
   public static void main (String args[]) {
   byte b1 = 127; // 01111111
   byte b2 = 128; //10000000
   byte b3 = 200;
   char c = 128; // char는 singned/unsinged가 없으므로 byte대신에 char를 써도 된다.

   System.out.println(b1); // 127
   System.out.println(b2); // -128
   System.out.println(b3); // -56
   System.out.println((int)c); // 128;
   System.out.println(unsignedByteToInt(b1)); // 127
   System.out.println(unsignedByteToInt(b2)); // 128
   System.out.println(unsignedByteToInt(b3)); // 200
 
   System.out.println(unsignedIntToLong(0xFFFFFFFF) // 4294967295 (부호 없는 32비트 int형의 최대값)
   System.out.println(unsignedIntToLong(0x7FFFFFFF) // 2147483647 (부호 있는 32비트 int형의 최대값)
}

   public static int unsignedByteToInt(byte b) {
      // 먼저 b & 0xFF를 해서 byte타입이 아닌 이진수 0x10000000을 만든후 int로 casting을 한다.
      return (int) b & 0xFF; // 10000000(128) & 11111111(0xFF) = 10000000 (128)
   }
   public static long unsignedIntToLong (int i) {
      return i & 0xFFFFFFFFL;
      //return (long) i & 0xFFFFFFFF;
   }
}


HEX 출력

    public static String byte2hex(byte b) {
        final String hex[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", };
        String h1 = hex[((b >> 4) & 0x0f)];
        String h2 = hex[(b & 0x0f)];
        return h1 + h2;
    }

    public static String byteToHexString(byte[] b) {
        String d = "";
        if (b == null)
            return "null";
        for(int i = 0; i < b.length; i++) {
            d += "0x" + byte2hex(b[i]) + " ";
        }

        return d;
    }

String을 byte[]로 변환

    public static byte[] toBytes(String digits, int radix) 
            throws IllegalArgumentException, NumberFormatException {
        if (digits == null) {
            return null;
        }
        if (radix != 16 && radix != 10 && radix != 8) {
            throw new IllegalArgumentException("For input radix: \"" + radix + "\"");
        }
        int divLen = (radix == 16) ? 2 : 3;
        int length = digits.length();
        if (length % divLen == 1) {
            throw new IllegalArgumentException("For input string: \"" + digits + "\"");
        }
        length = length / divLen;
        byte[] bytes = new byte[length];
        for (int i = 0; i < length; i++) {
            int index = i * divLen;
            bytes[i] = (byte)(Short.parseShort(digits.substring(index, index+divLen), radix));
        }
        return bytes;
    }
    // 사용법
    public static void main (String args[]) {
        String hex = "0001020304050607";
        byte[] byteArray = toBytes(hex, 16); // {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}
    }


'Android > 클래스' 카테고리의 다른 글

[번역]자바 Enum의 10가지 예제  (0) 2013.07.18
PendingIntent  (0) 2013.06.27
AsyncTask  (0) 2013.02.14
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함