<<
, >>
: 자리수를 이동하는 연산자
좌측피연산자가 양수일 경우엔 연산 후 좌측비트를 0으로 채운다.
좌측피연산자가 음수일 경우엔 연산 후 좌측비트를 1로 채운다. (부호를 유지하기 위함)
public class ch3_OperatorEx30 {
// 10진 정수를 2진수로 변환하는 메서드
static String toBinaryString(int x){
String zero = "00000000000000000000000000000000";
String tmp = zero + Integer.toBinaryString(x);
return tmp.substring(tmp.length()-32);
}
public static void main(String[] args) {
int dec = 8;
System.out.printf("%d >> %d = %4d \t%s%n", dec, 0, dec >> 0, toBinaryString(dec >> 0));
System.out.printf("%d >> %d = %4d \t%s%n", dec, 1, dec >> 1, toBinaryString(dec >> 1));
System.out.printf("%d >> %d = %4d \t%s%n", dec, 2, dec >> 2, toBinaryString(dec >> 2));
System.out.printf("%d << %d = %4d \t%s%n", dec, 0, dec << 0, toBinaryString(dec << 0));
System.out.printf("%d << %d = %4d \t%s%n", dec, 1, dec << 1, toBinaryString(dec << 1));
System.out.printf("%d << %d = %4d \t%s%n", dec, 2, dec << 2, toBinaryString(dec << 2));
System.out.println();
dec = -8;
System.out.printf("%d >> %d = %4d \t%s%n", dec, 0, dec >> 0, toBinaryString(dec >> 0));
System.out.printf("%d >> %d = %4d \t%s%n", dec, 1, dec >> 1, toBinaryString(dec >> 1));
System.out.printf("%d >> %d = %4d \t%s%n", dec, 2, dec >> 2, toBinaryString(dec >> 2));
System.out.printf("%d << %d = %4d \t%s%n", dec, 0, dec << 0, toBinaryString(dec << 0));
System.out.printf("%d << %d = %4d \t%s%n", dec, 1, dec << 1, toBinaryString(dec << 1));
System.out.printf("%d << %d = %4d \t%s%n", dec, 2, dec << 2, toBinaryString(dec << 2));
}
x << n은 x * 2^n의 결과와 같다.
x >> n은 x / 2^n의 결과와 같다.
그냥 곱셈, 나눗셈을 이용해도 결과는 같지만 이런 식이 있는 이유 : 속도가 더 빠름
그렇지만 가독성이 떨어지기 때문에 속도가 중요한 경우에만 사용하는 것이 좋음
8 >> 0 = 8 00000000000000000000000000001000
8 >> 1 = 4 00000000000000000000000000000100
8 >> 2 = 2 00000000000000000000000000000010
8 << 0 = 8 00000000000000000000000000001000
8 << 1 = 16 00000000000000000000000000010000
8 << 2 = 32 00000000000000000000000000100000
-8 >> 0 = -8 11111111111111111111111111111000
-8 >> 1 = -4 11111111111111111111111111111100
-8 >> 2 = -2 11111111111111111111111111111110
-8 << 0 = -8 11111111111111111111111111111000
-8 << 1 = -16 11111111111111111111111111110000
-8 << 2 = -32 11111111111111111111111111100000
16 진수에서 한자리씩 추출할 때 아래와 같은 식을 이용할 수 있다.
public static void main(String[] args) {
int dec = 1234;
int hex = 0xABCD;
int mask = 0xF;
System.out.printf("hex=%X%n", hex);
System.out.printf("%X%n", hex & mask);
hex = hex >> 4;
System.out.printf("%X%n", hex & mask);
hex = hex >> 4;
System.out.printf("%X%n", hex & mask);
hex = hex >> 4;
System.out.printf("%X%n", hex & mask);
}
hex=ABCD
D
C
B
A