Home > Backend Development > C++ > 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
Release: 2023-09-08 22:53:06
forward
1235 people have browsed it

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));
}
Copy after login

Output

Binary representation of 0.156250 has 6 set bits
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template