fork download
  1. #include <stdio.h>
  2.  
  3. // Count the number of zeros in a specific amount of bits starting at a specific offset
  4. // value is the original value
  5. // offset is the offset in bits
  6. // bits is the number of bits
  7. unsigned int count_zeros(unsigned int value, unsigned int offset, unsigned int bits)
  8. {
  9. // Get the bits we're interested in the rightmost position
  10. value >>= offset;
  11.  
  12. unsigned int counter = 0; // Zero-counter
  13. for (unsigned int i = 0; i < bits; ++i)
  14. {
  15. if ((value & (1 << i)) == 0)
  16. {
  17. ++counter; // Bit is a zero
  18. }
  19. }
  20.  
  21. return counter;
  22. }
  23.  
  24. int main(void)
  25. {
  26. printf("Result of count_zeros(0xa5, 2, 4) = %u\n", count_zeros(0xa5, 2, 4));
  27. }
  28.  
Success #stdin #stdout 0s 9432KB
stdin
Standard input is empty
stdout
Result of count_zeros(0xa5, 2, 4) = 2