Advertisement
vencinachev

BitwiseOperations

Jul 8th, 2021
769
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.73 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. void setBit(int* mask, int n)
  5. {
  6.     *mask |= (1 << n);
  7. }
  8.  
  9. void eraseBit(int* mask, int n)
  10. {
  11.     *mask &= ~(1 << n);
  12. }
  13.  
  14. int isSet(int mask, int n)
  15. {
  16.     return mask & (1 << n);
  17. }
  18.  
  19. int onesCount(int mask)
  20. {
  21.     int count = 0;
  22.     for (int i = 0; i < sizeof(int) * 8; i++)
  23.     {
  24.         if (isSet(mask, i))
  25.         {
  26.             count++;
  27.         }
  28.     }
  29.     return count;
  30. }
  31.  
  32. int zerosCount(int mask)
  33. {
  34.     return sizeof(int) * 8 - onesCount(mask);
  35. }
  36.  
  37. int main()
  38. {
  39.     int prisustviq = 0;
  40.     setBit(&prisustviq, 1);
  41.     setBit(&prisustviq, 3);
  42.     setBit(&prisustviq, 0);
  43.     //eraseBit(&prisustviq, 3);
  44.     printf("%d\n", onesCount(prisustviq));
  45.     return 0;
  46. }
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement