반응형
참고
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;
}
반응형
'개발 > C, C++' 카테고리의 다른 글
여러가지 나머지 연산 방법 테스트 (0) | 2023.08.15 |
---|---|
C, C++ - 비트 교환 (Change Some Bits) (0) | 2023.08.15 |
C, C++ - 2차원 비트맵 뒤집기, 회전하기 (Rotate, Flip 2D Bitmap) (0) | 2023.07.30 |
C, C++ - 1차원 비트 회전하기 (Rotate Bits of a Number) (0) | 2023.07.30 |
C, C++ - 1 비트 개수 세기 (Bit Counter) (0) | 2023.07.29 |
댓글