-
변수의 각 비트를 컨트롤 하기Procademy 2017. 4. 15. 09:51unsigned short (16bit) 변수의 각 비트를 컨트롤 하기- unsigned short 변수 = 0 으로 초기값 가짐.- 키보드로 1 ~ 16의 비트 자리 입력을 받음- 1 / 0 을 사용자로부터 받아서 지정된 자리의 비트를 0 또는 1로 바꿔줌.- 다른 위치에 입력된 기존 데이터는 보존이 되어야 함
비트 연산자를 이용하여 각 자리의 비트를 1로 설정하거나, 0으로 제거하고, 토글시키거나, 확인할 수 있다.
비트를 1로 설정하기
number |= 1 << x;
비트를 0으로 설정하기
number &= ~(1 << x);
비트를 반전시키기
number ^= 1 << x;
n번째의 비트를 x로 설정하기
number ^= (-x ^ number) & (1 << n);
n번째의 비트를 x를 1로하면 설정, x를 0으로 하면 해제
비트 설정이 자주 쓰이는 곳에는 아래처럼 헤더파일을 만들어놓고 이용한다면 간편하게 쓸 수 있다.
/* a=target variable, b=bit number to act upon 0-n */ #define BIT_SET(a,b) ((a) |= (1<<(b))) #define BIT_CLEAR(a,b) ((a) &= ~(1<<(b))) #define BIT_FLIP(a,b) ((a) ^= (1<<(b))) #define BIT_CHECK(a,b) ((a) & (1<<(b))) /* x=target variable, y=mask */ #define BITMASK_SET(x,y) ((x) |= (y)) #define BITMASK_CLEAR(x,y) ((x) &= (~(y))) #define BITMASK_FLIP(x,y) ((x) ^= (y)) #define BITMASK_CHECK(x,y) (((x) & (y)) == (y))
내 코드
#include <stdio.h> void printToBinary(int num, int length); void bitOnOff(unsigned short * number, int onOff, int location); int main() { unsigned short number = 0; int changeLocation = 0; int onOff = 1; printf("Location of the bit : "); scanf("%d",&changeLocation); printf("OFF/ON [0,1] : "); scanf("%d", &onOff); bitOnOff(&number,onOff,changeLocation); printf("Number in decimal : %d\n",number); printf("Number in Binary : "); printToBinary(number,16); return 0; } void bitOnOff(unsigned short * number, int onOff, int location) { location --; // OFF if (onOff == 0 ) { *number &= ~(1 << location); } // ON else { *number |= 1 << location; } } void printToBinary(int num, int length) { int i = length; for (i ; i>=0; --i) { printf("%d", (num >> i) & 1 ); } printf("\n"); }
참고 자료
http://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c-c
http://stackoverflow.com/questions/920511/how-to-visualize-bytes-with-c-c
'Procademy' 카테고리의 다른 글
File Packing [패킹 프로그램] (0) 2017.04.24 변수를 바이트 단위로 설정하기 (0) 2017.04.15 Sin 그래프 출력해보기 (0) 2017.04.15