JAVA/JAVA 기초

[JAVA 기초] 비트 전환 연산자

큐범 2021. 7. 16. 09:31

비트 전환 연산자 ~

비트 전환 연산자는 2진수로 표현했을 때, 0은 1 1은 0으로 표현한다.

x ~x
1 0
0 1
public static void main(String[] args) {
		byte p = 10;
		byte n = -10;
		
		System.out.printf("p = %d \t%s%n", p, toBinaryString(p));
		System.out.printf("~p = %d \t%s%n", ~p, toBinaryString(~p));
		System.out.printf("~p+1 = %d \t%s%n", ~p+1, toBinaryString(~p+1));
		System.out.printf("~~p = %d \t%s%n", ~p+1, toBinaryString(~~p));
		System.out.println();
		System.out.printf(" n = %d%n", n);
		System.out.printf("~(n-1)=%d%n", ~(n-1));
	}

	private static String toBinaryString(int x) {
		String zero = "00000000000000000000000000000000";
		String temp = zero + Integer.toBinaryString(x);
		return temp.substring(temp.length()-32);
	}
    //결과
p = 10 	    00000000000000000000000000001010
~p = -11 	11111111111111111111111111110101
~p+1 = -10 	11111111111111111111111111110110
~~p = -10 	00000000000000000000000000001010

 n = -10
~(n-1)=10

p에 대한 음의 정수를 얻으려면 ~p+1을 하면 얻을 수 있고, 음의 정수를 얻기 위해서는 ~(n-1)을 계산하면 된다.

 

출처 : JAVA의 정석 - (남궁성지음)