如何在 C 中計算浮點數字中置位位的數量?


在這個問題中,給定一個浮點值。我們必須找到其二進位制表示中設定位的數量。

例如,如果浮點數為 0.15625,那麼有六個設定位。一個典型的 C 編譯器使用單精度浮點數表示。因此它將如下所示。

為了將其轉換為其位值,我們必須將數字放入一個指標變數中,然後將指標強制轉換為 char* 型別資料。然後逐個處理每個位元組。然後,我們可以計算每個 char 的設定位。

示例

#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));
}

輸出

Binary representation of 0.156250 has 6 set bits

更新於: 30-7-2019

423 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.