您如何计算浮点数中设置的位数?

5 c floating-point

如何使用C函数计算浮点数中设置的位数?

ram*_*ion 6

#include <stdio.h>  /* for printf() */
#include <limits.h> /* for CHAR_BIT */

int main(void) {
  /* union method */
  {
    /* a union can only be initialized for the first option in the union */
    union { float f; char cs[sizeof(float)]; } const focs = { 1.0 };
    int j,k;
    int count = 0;
    for (j = 0; j < sizeof(float); j++)
    {
      char const byte = focs.cs[j];
      for (k = 0; k < CHAR_BIT; k++)
      {
        if ((1 << k) & byte)
        {
          count++;
        }
      }
    }
    printf("count(%2.1f) = %d\n", focs.f, count);
  }
  /* cast method */
  {
    float const f = 2.5;
    int j,k; 
    int count = 0;
    for (j = 0; j < sizeof(float); j++)
    {
      char const byte = ((char *)&f)[j];
      for (k = 0; k < CHAR_BIT; k++)
      {
        if ((1 << k) & byte)
        {
          count++;
        }
      }
    }
    printf("count(%2.1f) = %d\n", f, count);
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)


Adr*_*iuk 2

您的意思是数字的 IEEE-754 单精度表示中设置的位?如果是这样,请将其转换为 int (float 和 int 都是 32 位宽)并进行常规位计数:SO Question #109023

  • 转换为 int 将会截断并转换,而不是为您提供原始表示形式。 (2认同)
  • 好点子。所以更好的解决方案是联合它或浮动 f; *(整数*)&amp;f (2认同)