Skip to content

Instantly share code, notes, and snippets.

@neuro-sys
Created May 3, 2011 15:50
Show Gist options
  • Save neuro-sys/953593 to your computer and use it in GitHub Desktop.
Save neuro-sys/953593 to your computer and use it in GitHub Desktop.
bitwise unwise
void print_as_binary(unsigned int num)
{
unsigned int mask = (1 << 31);
int i;
for (i = 1; i <= 32; i++) {
printf("%d", (num & mask) ? 1 : 0);
mask >>= 1;
if (i % 4 == 0)
putchar(' ');
}
}
int FindFirstSet(unsigned BitMap, unsigned start)
{
unsigned Mask = (1 << start);
while (Mask) {
if (BitMap & Mask) return start;
++start;
Mask <<= 1;
}
return -1;
}
int FindFirstClr(unsigned BitMap, unsigned start)
{
return FindFirstSet(~BitMap, start);
}
int SetBit(unsigned BitMap, unsigned position)
{
return BitMap | (1 << position);
}
int ClrBit(unsigned BitMap, unsigned position)
{
return BitMap & ~(1 << position);
}
int tolower(int c)
{
return c | 0x20;
}
int toupper(int c)
{
return c & ~0x20;
}
int switchCase(int c)
{
return (c & 0x20) ? toupper(c) : tolower(c);
}
int CharToInt(char *num)
{
int i = 0;
int sum = 0;
while (num[i] != '\0') {
sum = (sum * 10) + (num[i] & 0x0F);
i++;
}
return sum;
}
int ToDate(int month, int day, int year)
{
return month << 12 | day << 7 | year;
}
int ExtractMonth(int pdate)
{
return pdate >> 12;
}
int ExtractDay(int pdate)
{
return pdate >> 7 & 0x1F;
}
int ExtractYear(int pdate)
{
return pdate & 0x7F;
}
int CntBits(int num)
{
int count = 0;
do {
if (num & 1) count++;
num >>= 1;
} while (num);
return count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment