비트 단위 연산자

Chae Yun·2021년 7월 24일
0

연산자

목록 보기
3/3
public class Test021
{
	public static void main(String[] args)
	{
		int a=10, b= -10;

		System.out.printf("~a : %d\n", ~a);
		System.out.printf("~b : %d\n", ~b); //비트 반전(부정)

	}
}
~a : -11
~b : 9
계속하려면 아무 키나 누르십시오 . . .



a=1000001010
        11110101 (반전) : -11

b=-10   10000010102의 보수
              111101011의 보수 먼저 취하고(비트열 반전)
			  111101101더하기
*/
public class Test022
{
	public static void main(String [] args)
	{
		int a = 13, b = 7;
		int c,d,e;

		//연산 및 처리
		c = a & b;
		d = a | b;
		e = a ^ b;

		//결과 출력
		System.out.printf("a&b : %d\n", c);
		System.out.printf("a|b : %d\n", d);
		System.out.printf("a^b : %d\n", e);

🧐 & 두 개 각 자리가 같으면 1 다르면 0
|는 or개념
^는 같으면 0 다르면1

13 => 00001101
& 7 => 00000111
00000101 => 5(1 + 4)

13 => 00001101
| 7 => 00000111
00001111 => 15(1 + 2 + 4 + 8)

13 => 00001101
^ 7 => 00000111
00001010 => 10(2 + 8)

●비트 shift 연산

비트 shift 연산자 (방향성)
'<<' : '>>>'과 짝
'<<' : 비트 열을 오른쪽으로 이동하고 빈 공간은 0으로 채운다
'>>' : 양수 - 오른쪽을 이동하고 빈 공간은 0으로 채운다
음수 - 오른쪽으로 이동하여 빈 공간은 1로 채운다

public class Test023 {

	public static void main(String[] args) {
					  //						     |
		int x = 128;  //  00000000 00000000 00000000 10000000
																		//     |
		System.out.printf("x << 3 : %d\n", x << 3);  // 00000000 00000000 00000100 00000000   (1024) 
		System.out.printf("x * 8 : %d\n", x * 8);
		// x << 3 : 1024
		// x * 8 : 1024
													 //								  |
		System.out.printf("x >> 3 : %d\n", x >> 3);  // 00000000 00000000 00000000 00010000    (16)
		System.out.printf("x / 8 : %d\n", x / 8);
		// x >> 3 : 16
		// x / 8 : 16
													    // |
		System.out.printf("x << 24 : %d\n", x << 24);   // 10000000 00000000 00000000 00000000
		// ==> x << 24 : -2147483648

		System.out.printf("x << 25 : %d\n", x << 25);
		// ==> x << 25 : 0
		
		System.out.printf("x << 26 : %d\n", x << 26);
		System.out.printf("x << 27 : %d\n", x << 27);
		System.out.printf("x << 28 : %d\n", x << 28);
		System.out.printf("x << 29 : %d\n", x << 29);
		System.out.printf("x << 30 : %d\n", x << 30);
		System.out.printf("x << 31 : %d\n", x << 31);
		// ==> x << 26 ~ 31 : 0

		System.out.printf("x << 32 : %d\n", x << 32);
		// ==> x << 32 : 128
		

	}

}

/*
	실행 결과

x << 3 : 1024
x * 8 : 1024
x >> 3 : 16
x / 8 : 16
x << 24 : -2147483648
x << 25 : 0
x << 26 : 0
x << 27 : 0
x << 28 : 0
x << 29 : 0
x << 30 : 0
x << 31 : 0
x << 32 : 128
계속하려면 아무 키나 누르십시오 . . .

*/

📝
x<<n 은 x*2^n 과 같다
x>>n 은 x/2^n 과 같다

0개의 댓글