Advertisement
Guest User

Count Bits in Numeric Types

a guest
Feb 23rd, 2020
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. #include <stdio.h>
  2. #define SIZE 5
  3.  
  4. #define m_count(arr, res, type)\
  5. {\
  6. unsigned type mask;\
  7. type temp;\
  8. int i, count = 0;\
  9. type *p = (type *)arr;\
  10. \
  11. for(i=0; i < SIZE ; i++)\
  12. {\
  13. mask = 1;\
  14. temp = p[i];\
  15. while(mask)\
  16. {\
  17. if(temp & mask)\
  18. {\
  19. count++;\
  20. }\
  21. mask = mask << 1;\
  22. }\
  23. }\
  24. res = count;\
  25. }
  26.  
  27. typedef enum {t_int, t_double, t_char} types;
  28.  
  29. int my_count(void *, types);
  30.  
  31. int main()
  32. {
  33. int i ,temp;
  34. int arr[SIZE];
  35.  
  36. printf("Please enter numbers: ");
  37. for(i=0; i<SIZE; i++)
  38. {
  39. scanf("%d", &temp);
  40. arr[i] = temp;
  41. }
  42.  
  43. my_count((void *)arr, t_int);
  44. return 0;
  45. }
  46.  
  47. int my_count(void *data, types t)
  48. {
  49. int res = 0;
  50. if(t == t_int)
  51. {
  52. m_count(data, res, int);
  53. }
  54. if(t == t_char)
  55. {
  56. m_count(data, res, char);
  57. }
  58.  
  59. printf("res bits: %d ", res);
  60.  
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement