본문 바로가기
개발/C, C++

C, C++ - 비트 뒤집기 (Reverse Bits)

by 피로물든딸기 2023. 7. 30.
반응형

C, C++ 전체 링크

삼성 C형 전체 링크

 

참고

- 비트 단위로 출력하기

- 1 비트 개수 세기

 

1 비트 개수를 세는 방법을 응용하면 비트를 뒤집는 것도 가능하다.

long, int, short, char ver 구현을 참고하자.

#include <stdio.h>

typedef unsigned long long int ll;

template <typename T>
void printBitNumber(T number)
{
	unsigned int bitSize = sizeof(number) * 8;
	T mask = (1ull) << (bitSize - 1);

	printf("%d", (number & mask) == mask);

	mask = (1ull) << (bitSize - 2);
	for (int i = 1; i < bitSize; i++)
	{
		printf("%d", (number & mask) == mask);
		mask >>= 1;
		if (i % 8 == 7) printf(" ");
	}
	putchar('\n');
}

ll getBitConvertLong(ll number)
{
	ll convert = number;

	convert = (convert & 0x5555555555555555) <<  1 | (convert & 0xAAAAAAAAAAAAAAAA) >>  1; //0101 = 5, 1010 = A
	convert = (convert & 0x3333333333333333) <<  2 | (convert & 0xCCCCCCCCCCCCCCCC) >>  2; //0011 = 3, 1100 = C
	convert = (convert & 0x0F0F0F0F0F0F0F0F) <<  4 | (convert & 0xF0F0F0F0F0F0F0F0) >>  4;
	convert = (convert & 0x00FF00FF00FF00FF) <<  8 | (convert & 0xFF00FF00FF00FF00) >>  8;
	convert = (convert & 0x0000FFFF0000FFFF) << 16 | (convert & 0xFFFF0000FFFF0000) >> 16;
	convert = (convert & 0x00000000FFFFFFFF) << 32 | (convert & 0xFFFFFFFF00000000) >> 32;

	return convert;
}

int getBitConvertInt(int number)
{
	int convert = number;

	convert = (convert & 0x55555555) <<  1 | (convert & 0xAAAAAAAA) >>  1; //0101 = 5, 1010 = A
	convert = (convert & 0x33333333) <<  2 | (convert & 0xCCCCCCCC) >>  2; //0011 = 3, 1100 = C
	convert = (convert & 0x0F0F0F0F) <<  4 | (convert & 0xF0F0F0F0) >>  4;
	convert = (convert & 0x00FF00FF) <<  8 | (convert & 0xFF00FF00) >>  8;
	convert = (convert & 0x0000FFFF) << 16 | (convert & 0xFFFF0000) >> 16;

	return convert;
}

short getBitConvertShort(short number)
{
	short convert = number;

	convert = (convert & 0x5555) << 1 | (convert & 0xAAAA) >> 1;
	convert = (convert & 0x3333) << 2 | (convert & 0xCCCC) >> 2; 
	convert = (convert & 0x0F0F) << 4 | (convert & 0xF0F0) >> 4;
	convert = (convert & 0x00FF) << 8 | (convert & 0xFF00) >> 8;
	
	return convert;
}

char getBitConvertChar(char number)
{
	char convert = number;

	convert = (convert & 0x55) << 1 | (convert & 0xAA) >> 1; 
	convert = (convert & 0x33) << 2 | (convert & 0xCC) >> 2; 
	convert = (convert & 0x0F) << 4 | (convert & 0xF0) >> 4;

	return convert;
}

int main(void)
{
	ll lx = 123456701234567;
	int ix = 98765432;
	short sx = 12345;
	char cx = 57;

	printBitNumber(lx);
	printBitNumber(getBitConvertLong(lx));
	putchar('\n');
	printBitNumber(ix);
	printBitNumber(getBitConvertInt(ix));
	putchar('\n');
	printBitNumber(sx);
	printBitNumber(getBitConvertShort(sx));
	putchar('\n');
	printBitNumber(cx);
	printBitNumber(getBitConvertChar(cx));
	putchar('\n');

	return 0;
}

반응형

댓글