C# 程式用來計算數字中總的設定位


我們示例中的數字是 11,即二進位制 −

1101

在 1101 中,總設定位數為 3;要找出這一數值,需建立一個迴圈,直至它不等於 0。此處,我們的數字為 11,即十進位制 −

while (num>0) {
   cal += num & 1;
   num >>= 1;
}

示例

要計算數字中的總設定位,請使用以下程式碼。

動態演示

using System;
public class Demo {
   public static void Main() {
      int cal = 0;
      // Binary is 1011
      int num = 11;
      while (num>0) {
         cal += num & 1;
         num >>= 1;
      }
      // 1 bits in 1101 are 3
      Console.WriteLine("Total bits: "+cal);
   }
}

輸出

Total bits: 3

更新於: 2020 年 6 月 19 日

234 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.