프로그래밍/C++

[C/C++] 특정 비트 On/Off 밑 해당 비트 값 얻기

성야 2016. 8. 17. 12:53

비트 연산자를 통한 각 비트의 설정 값(1, 0) 얻어오기

int getAbit(unsigned short x, int n) 
{
 return (x & (1 << n)) >> n;
}

 

각 비트 값 설정

unsigned short setAbit(unsigned short x, int n, int value) 
{
 if (value == 1)
  return (unsigned short) (x | (1 << n));
 else
  return (unsigned short) (x & (~(1 << n)));
}