本文へスキップ
製品デスクトップツールTASTECAD図面の確認TASTEFILESファイル管理TASTEFTPファイル転送TASTESSHリモートワークスペースTASTEZIP圧縮と展開TASTEWINMファイル管理開発ツールTASTECODERust 統合開発環境TASTESTUDIO統合開発・テスト環境TASTEETLデータ統合(ETL)サーバーTASTEREMOTEリモートデスクトップサーバーTASTEGEO空間情報サーバーTASTEMAILメールワークスペース投資TASTESTOCK株式自動売買デスクトップアプリはじめるダウンロードドキュメント購入すべての製品
マーケットプレイス
ニュース
技術ニュース今日の開発ニュース開発ドキュメントプログラミング言語RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWebフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngularサーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Expressアプリ・デスクトップ フレームワークTauriFlutterReact NativeElectronアルゴリズムアルゴリズムの基礎主要アルゴリズム発展アルゴリズム実務のアルゴリズム
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケースコミュニティガイド
協業技術移転ウェブサイト構築デスクトップアプリ構築リリース・決済パイプライン販売パートナーお問い合わせ
サービスリモートデスクトップインストールパッケージのカスタマイズ
TASTEDEV
製品

デスクトップツール

TASTECAD複雑な図面を、軽やかにひらくTASTEFILES必要なファイルだけを、最速でTASTEFTPファイルが行き交う、いちばん端正な道TASTESSHサーバーとあなたを、より確かにつなぐTASTEZIPより速くまとめ、より安全にひらくTASTEWINM2つの画面で整理する、キーボード中心のファイルマネージャー

開発ツール

TASTECODERust アプリの編集・ビルド・デバッグ・テストまでひとつのウィンドウでTASTESTUDIO編集からリモートテスト、承認した AI 修正までTASTEETL値を見ながら、データを運ぶ

サーバー

TASTEREMOTE自社サーバーで運用するリモートデスクトップTASTEGEOGeoServer 互換の空間情報サーバーを Rust で作り直しますTASTEMAILメールの主導権を、もう一度自分の手に

投資

TASTESTOCKいつ・何を。自分で決めたルールどおりに動く株式自動売買

はじめる

ダウンロード全製品の最新版ドキュメント各製品の使い方購入サブスクリプション・永久ライセンスすべての製品全製品を一覧で
すべての製品
マーケットプレイスニュース
技術

ニュース

今日の開発ニュース言語・フレームワーク・GitHub・AI の公式発表開発ドキュメント言語・フレームワーク・アルゴリズムのガイド

プログラミング言語

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

フレームワーク

Webフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngular
サーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
アプリ・デスクトップ フレームワークTauriFlutterReact NativeElectron

アルゴリズム

アルゴリズムの基礎計算量解析 · ソート · 探索 · 基本データ構造 · 木構造とヒープ主要アルゴリズムグラフ探索 · 最短経路と最小全域木 · 動的計画法 · 貪欲法 · 分割統治法 · バックトラッキング発展アルゴリズム文字列アルゴリズム · 数学と整数論 · ビット演算 · セグメント木 · Union-Find実務のアルゴリズムコーディング面接対策 · LRUキャッシュ · レート制限 · コンシステントハッシュ法
開発ドキュメントをすべて見る
コミュニティ
プロジェクトビルダーと作品を探す開発ログ決定と試行錯誤プロンプト再利用できる指示AIツールの問題Claude・Codex・Gemini の問題と回避策ショーケース完成した成果コミュニティガイドオープンにつくる方法
協業
技術移転Rust・egui でネイティブアプリを作るウェブサイト構築10言語、アカウント、ドキュメントとダウンロードデスクトップアプリ構築Rust・egui、WebView なしリリース・決済パイプライン署名・MSI・deb・rpm・AppImage・ハッシュ販売パートナー紹介して決済額の30%お問い合わせ構築・提携・投資のご相談
サービス
リモートデスクトップブラウザから自分のパソコンへインストールパッケージのカスタマイズ必要な機能だけ、設定は事前に
購入
JA
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
ログイン
ログイン
TASTEDEV

小さなツールから、より良い開発へ。

support@tastedev.netTASTEDEVを支援
製品製品ラインナップ購入ドキュメントダウンロードマーケットプレイスサポート
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケース
ポリシー会社概要プライバシーポリシー利用規約サブスクリプション規約返金ポリシーコミュニティガイドライン
アカウントログイン新規登録
訪問者
今日
昨日
累計閲覧
商号
GXSOFT
代表者
CHOI YOUNG GU
事業者登録番号
853-44-00368
所在地
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
電話
+82-10-4404-1523
メール
whitecalvin@tastedev.net
個人情報保護責任者
CHOI YOUNG GU

© 2026 TASTEDEV製品情報は検証済みの開発ソースに基づいています。リリース・改善中

ビット演算 ドキュメント
ビット演算
ConceptsHow It WorksImplementationComplexityPractice ProblemsReal-World Use
ディスカッション

ビット演算 ガイド · 3/6

Implementation

この章は現在、英語でのみ提供しています。

This chapter implements two core routines: popcount, which counts set bits, and a subset enumerator driven by bitmasks. We walk through the Python version line by line, then port the same routine to C++, Java and TypeScript, noting where integer width and shift rules differ.

Python

from collections.abc import Iterator, Sequence


def popcount(x: int) -> int:
    if x < 0:
        raise ValueError("x must be non-negative")
    count = 0
    while x:
        x &= x - 1          # clear the lowest set bit
        count += 1
    return count


def subsets(items: Sequence) -> Iterator[tuple[int, list]]:
    n = len(items)
    for mask in range(1 << n):                  # 0 .. 2^n - 1
        chosen = [items[i] for i in range(n) if (mask >> i) & 1]
        yield mask, chosen


def subsets_of_size(items: Sequence, k: int) -> list[list]:
    return [chosen for mask, chosen in subsets(items) if popcount(mask) == k]


if __name__ == "__main__":
    for mask, chosen in subsets(["a", "b", "c"]):
        print(format(mask, "03b"), popcount(mask), chosen)
    print(subsets_of_size(["a", "b", "c", "d"], 2))
    assert all(popcount(m) == m.bit_count() for m in range(1 << 12))
  • popcount rejects negative input. Python integers are unbounded and a negative value behaves as if it had infinitely many leading 1s, so x &= x - 1 would never reach 0.
  • x &= x - 1 clears the lowest set bit; the number of rounds is the answer.
  • range(1 << n) yields every n-bit mask, from 0 to 2^n - 1.
  • (mask >> i) & 1 tests bit i; when it is 1, items[i] is in the subset.
  • yield produces subsets one at a time, so all 2^n of them never sit in memory together.
  • subsets_of_size keeps masks whose popcount is k, giving all k-combinations.
  • The final assert checks against the built-in int.bit_count() (Python 3.10+), which is what you should use in production.

C++

Use unsigned types for masks. Signed overflow and shifting by the full width or more (1u << 32) are undefined behavior. C++20 adds std::popcount in <bit>, and GCC and Clang offer __builtin_popcount and __builtin_ctz.

#include <cstdint>
#include <iostream>
#include <string>
#include <vector>

int popcount(std::uint32_t x) {
    int count = 0;
    while (x != 0) {
        x &= x - 1;  // clear the lowest set bit
        ++count;
    }
    return count;
}

void printSubsets(const std::vector<std::string>& items) {
    const int n = static_cast<int>(items.size());  // n < 32
    for (std::uint32_t mask = 0; mask < (1u << n); ++mask) {
        std::cout << mask << " (" << popcount(mask) << "):";
        for (int i = 0; i < n; ++i)
            if ((mask >> i) & 1u) std::cout << ' ' << items[i];
        std::cout << '\n';
    }
}

int main() { printSubsets({"a", "b", "c"}); }
この章について質問がありますか?
前の章How It Works次の章Complexity

Java

int is 32 bits and long is 64. >> copies the sign bit while >>> shifts in zeros. Only the low 5 bits of an int shift count are used, so 1 << 32 is 1; beyond 31 items switch to long and 1L << i. The standard library provides Integer.bitCount and Long.bitCount.

import java.util.ArrayList;
import java.util.List;

public class Subsets {
    static int popcount(int x) {
        int count = 0;
        while (x != 0) {
            x &= x - 1; // clear the lowest set bit
            count++;
        }
        return count;
    }

    static void printSubsets(List<String> items) {
        int n = items.size(); // n < 31 for int masks
        for (int mask = 0; mask < (1 << n); mask++) {
            List<String> chosen = new ArrayList<>();
            for (int i = 0; i < n; i++)
                if (((mask >>> i) & 1) == 1) chosen.add(items.get(i));
            System.out.println(mask + " (" + popcount(mask) + "): " + chosen);
        }
    }

    public static void main(String[] args) {
        printSubsets(List.of("a", "b", "c"));
        System.out.println(popcount(-1) + " " + Integer.bitCount(-1)); // 32 32
    }
}

TypeScript

Bitwise operators convert numbers to 32-bit signed integers first. So 1 << 31 is negative, and >>> 0 reinterprets a result as unsigned. Past 30 items use BigInt (1n << 40n), which supports every bitwise operator except >>>.

function popcount(x: number): number {
  let v = x >>> 0; // view as unsigned 32-bit
  let count = 0;
  while (v !== 0) {
    v = (v & (v - 1)) >>> 0; // clear the lowest set bit
    count++;
  }
  return count;
}

function printSubsets<T>(items: readonly T[]): void {
  const n = items.length; // n <= 30, otherwise use BigInt
  for (let mask = 0; mask < 1 << n; mask++) {
    const chosen = items.filter((_, i) => (mask >> i) & 1);
    console.log(`${mask} (${popcount(mask)}):`, chosen);
  }
}

printSubsets(["a", "b", "c"]);
console.log(popcount(-1)); // 32

Summary

All four versions count bits by clearing the lowest one with x &= x - 1, and enumerate subsets by looping mask from 0 to (1 << n) - 1 and testing (mask >> i) & 1. The differences are about integer width: in Python watch negative values, in C++ use unsigned types, in Java remember >>> and long, and in TypeScript remember the 32-bit conversion and >>> 0.

コメント 0件

人気のコメント順新しい順

ログイン · ログインするとコメントできます。