C언어 복습

김준혁·2026년 3월 17일

비트 연산 관련 예제

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <time.h>
#include <string.h>
#define SIZE 7
int main(void)
{
	unsigned int num;
	int pos = 0;
	char cmd[SIZE];
	printf("Register:");
	scanf("%x", &num);
	printf("Position:");
	scanf("%d", &pos);
	printf("Command:");
	scanf("%s", cmd);
	if (strcmp(cmd, "SET") == 0) {
		num |= (1 << pos);
	}
	else if (strcmp(cmd, "CLEAR") == 0) {
		num &= ~(1 << pos);
	}
	else if (strcmp(cmd, "TOGGLE") == 0) {
		num ^= (1 << pos);
	}
	else if (strcmp(cmd, "CHECK") == 0) {
		int bit = (num >> pos) & 1;
		printf("%d번 비트의 값은 %d입니다.\n", pos, bit);
	}

	printf("Result:0x%08X\n", num);
	printf("Binary:");
	for (int i = 31; i >= 0; i--) {
		int bit = (num >> i) & 1;
		printf("%d", bit);
		if (i % 4 == 0) {
			printf(" ");
		}
	}
	return 0;

}

1를 pos만큼 왼쪽으로 밀면(1<<pos) 정확히 pos자리만 1인 비트가 생성된다. 이 생성된 mask를 가지고서 비트 연산을 하면 된다.

profile
임베디드

0개의 댓글