자료구조&알고리즘/C++

🔍 비트마스크 : &= ~(1 << ind)와 ^= (1 << ind) 연산

geminanolja 2025. 3. 6. 19:33

✅ 1️⃣ 코드 전체 분석

#include<iostream>
using namespace std;
int main()
{
    int s = 15;  // 0b1111 (10진수 15)
    int a = 15;  // 0b1111 (10진수 15)
    cout << "s : " << s << endl;

    int ind = 2;  // 비트 조작할 위치 (2번째 비트)
    int ind2 = 1; // 비트 조작할 위치 (1번째 비트)

    s &= ~(1 << ind);  // 특정 비트를 0으로 만들기
    a ^= (1 << ind2);  // 특정 비트를 토글하기

    cout << "s : " << s << endl; // 결과: 11
    cout << "a : " << a << endl; // 결과: 13

    return 0;
}

✅ 2️⃣ 실행 예상 결과

s : 15
s : 11
a : 13

✅ 3️⃣ s &= ~(1 << ind); 분석

s &= ~(1 << ind);
  • s = 15 → 0b1111 (10진수 15)
  • ind = 2이므로 1 << ind 수행:
    1 << 2 = 0b0001 → 0b0100 (십진수 4)
    
  • ~(1 << ind) 연산 수행:
    ~(0b0100) = 0b1011 (십진수 -5)
    
  • s &= ~(1 << ind) 수행 (비트 AND):
    0b1111   (15)
    & 0b1011  (-5)
    ----------
      0b1011  (11)
    
  • 결과: s = 11 (0b1011)

즉, 2번째 비트(0b0100)를 0으로!


✅ 4️⃣ a ^= (1 << ind2); 분석

a ^= (1 << ind2);
  • a = 15 → 0b1111 (10진수 15)
  • ind2 = 1이므로 1 << ind2 수행:
    1 << 1 = 0b0010 (십진수 2)
    
  • a ^= 0b0010 수행 (XOR 연산):
    0b1111   (15)
    ^ 0b0010  (2)
    ----------
      0b1101  (13)
    
  • 결과: a = 13 (0b1101)

즉, 1번째 비트(0b0010)를 반전(1 → 0 또는 0 → 1)!


✅ 5️⃣ 최종 결과

연산 연산 결과 (비트) 결과 (십진수)

s &= ~(1 << 2); 0b1011 11
a ^= (1 << 1); 0b1101 13

✅ 6️⃣ 결론

  1. s &= ~(1 << ind); → 특정 비트를 0으로 만들기
  2. a ^= (1 << ind2); → 특정 비트를 반전(Toggle, 0↔1)
  3. s = 11, a = 13으로 변경됨.