티스토리 뷰




■ byte배열(물론 사이즈는 4)을 int로 바꾸는 메소드

1
2
3
4
5
6
7
8
public static int byte2Int(byte[] src) {
        int s1 = src[0] & 0xFF;
        int s2 = src[1] & 0xFF;
        int s3 = src[2] & 0xFF;
        int s4 = src[3] & 0xFF;
    
        return ((s1 << 24) + (s2 << 16) + (s3 << 8) + (s4 << 0));
}
 
 

■ long을 byte배열(물론 사이즈는 8)로 바꾸는 메소드 

1
2
3
4
5
6
7
8
9
10
11
12
13
public static byte[] long2Bytes(long l) {
        byte[] buf = new byte[8];
        buf[0] = (byte)( (l >>> 56) & 0xFF );
        buf[1] = (byte)( (l >>> 48) & 0xFF );
        buf[2] = (byte)( (l >>> 40) & 0xFF );
        buf[3] = (byte)( (l >>> 32) & 0xFF );  
        buf[4] = (byte)( (l >>> 24) & 0xFF );
        buf[5] = (byte)( (l >>> 16) & 0xFF );
        buf[6] = (byte)( (l >>>  8) & 0xFF );
        buf[7] = (byte)( (l >>>  0) & 0xFF );
    
        return buf;
}



■ 이건 또 다른 방식입니다. 위에 것이랑 거의 같습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
byte[] intToByte = new byte[4];  
  int a = 132;  
System.out.println("int를 byte 배열로 바꾼다.");  
intToByte[0] |= (byte)((a&0xFF000000)>>24);  
intToByte[1] |= (byte)((a&0xFF0000)>>16);  
intToByte[2] |= (byte)((a&0xFF00)>>8);  
intToByte[3] |= (byte)(a&0xFF);  
  
System.out.println("byte 배열을 int로 바꾼다");  
int result = 0;  
result |= (intToByte[0] & (int)0xFF)<<24;  
result |= (intToByte[1] & (int)0xFF)<<16;  
result |= (intToByte[2] & (int)0xFF)<<8;  
result |= (intToByte[3] & (int)0xFF);  
System.out.println("byte To Int is "+ result );


■ 16진수(Hex)로 된 Byte[] -> int로 변환하는 함수

1
2
3
4
5
6
7
8
9
10
11
12
byte[] hexbyte = new byte[3];
  
StringBuffer sb = new StringBufffer(hexbyte.length * 2);
String hexaDecimal;
  
for(int x = 0; x < hexbyte.length; x++)
{
     hexaDecimal = "0" + Intege.toHexString(0xff & hexbyte[x]);
     sb.append(hexaDecimal.substring(hexaDecimal.length()-2));
}
  
int decimal = Integer.parseInt(sb.toString(), 16);
 


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
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
글 보관함