Home  >  Article  >  Backend Development  >  How to count the number of digits in a floating point number in C?

How to count the number of digits in a floating point number in C?

PHPz
PHPzforward
2023-09-08 22:53:061165browse

In this question, a floating point value is given. We have to find the number of set bits in its binary representation.

For example, if the floating point number is 0.15625, there are six set bits. Typical C compilers use single-precision floating point representation. So it looks like this.

How to count the number of digits in a floating point number in C?

To convert to a bit value, we have to put the number into a pointer variable and then cast the pointer to char* type data. Then process each byte one by one. We can then calculate the set bits for each character.

Example

#include <stdio.h>
int char_set_bit_count(char number) {
   unsigned int count = 0;
   while (number != 0) {
      number &= (number-1);
      count++;
   }
   return count;
}
int count_float_set_bit(float x) {
   unsigned int n = sizeof(float)/sizeof(char); //count number of characters in the binary equivalent
   int i;
   char *ptr = (char *)&x; //cast the address of variable into char
   int count = 0; // To store the result
   for (i = 0; i < n; i++) {
      count += char_set_bit_count(*ptr); //count bits for each bytes ptr++;
   }
   return count;
}
main() {
   float x = 0.15625;
   printf ("Binary representation of %f has %u set bits ", x, count_float_set_bit(x));
}

Output

Binary representation of 0.156250 has 6 set bits

The above is the detailed content of How to count the number of digits in a floating point number in C?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete