Last active
March 17, 2021 19:58
-
-
Save boki1/2f5c4217bfc874d41a2a93cd61812113 to your computer and use it in GitHub Desktop.
Bitmap - School HW
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <limits.h> | |
#define BITS_IN_INT sizeof(int) * CHAR_BIT | |
#define BITMAP_SIZE (UCHAR_MAX + 1) / BITS_IN_INT | |
void set(int bitmap[], int bit, int val) | |
{ | |
int mask = 1 << bit % BITS_IN_INT; | |
int *b = bitmap + bit / BITS_IN_INT; | |
if (val) | |
*b |= mask; | |
else | |
*b &= ~mask; | |
} | |
int get(int bitmap[], int bit) | |
{ | |
int mask = 1 << bit % BITS_IN_INT; | |
int *b = bitmap + bit / BITS_IN_INT; | |
return !!(*b & mask); // make sure to return 0 | 1 | |
} | |
int count_ones(int num) | |
{ | |
int ones = 0; | |
for (; num; ones++) | |
num = num & (num - 1); | |
return ones; | |
} | |
int count(int bitmap[], int size) | |
{ | |
int ones = 0; | |
for (int i = 0; i < size; ++i) { | |
ones += count_ones(bitmap[i]); | |
} | |
return ones; | |
} | |
int main() | |
{ | |
int bitmap[BITMAP_SIZE] = { 0 }; | |
set(bitmap, 'a', 1); | |
printf("a: %d\n", get(bitmap, 'a')); | |
printf("b: %d\n", get(bitmap, 'b')); | |
printf("1's: %d\n", count(bitmap, BITMAP_SIZE)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment