cのビットワイズ演算子との作業方法
Bitwise operators in C++ are essential for manipulating individual bits in data, providing efficient control in low-level programming, embedded systems, and algorithmic optimizations. The six main operators are: & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), and >> (right shift), all operating on integral types at the bit level. For example, with unsigned char a = 5 (00000101) and b = 3 (00000011), a & b yields 1 (00000001), a | b gives 7 (00000111), a ^ b results in 6 (00000110), ~a produces 250 (11111010 in 8-bit), a << 1 equals 10 (multiplication by 2), and a >> 1 equals 2 (division by 2). Common techniques include checking if a number is odd or even using n & 1, toggling the k-th bit with n ^= (1 << k), setting the k-th bit via n |= (1 << k), clearing it with n &= ~(1 << k), and extracting a bit using (n >> k) & 1. XOR can swap two values without a temporary variable: a ^= b; b ^= a; a ^= b;, though this may affect code clarity. Counting set bits can be done manually with a loop or using GCC’s __builtin_popcount(n). Important considerations include using unsigned types to ensure predictable right-shift behavior, being aware of integer promotion and sign extension, and respecting operator precedence—parentheses are crucial, as in (flags & MASK) == VALUE to avoid errors due to == having higher precedence than &. Shifting by negative amounts or beyond bit width causes undefined behavior. A practical application is managing flags: constants like READ = 1, WRITE = 2, EXECUTE = 4 allow combining permissions with |, checking with &, and removing with ~, a pattern common in system programming. In summary, bitwise operators offer fast, precise bit-level control when used carefully with proper type selection, parentheses, and clear documentation, making them powerful tools in performance-critical and hardware-related code.
Working with bitwise operators in C++ is essential when you need to manipulate individual bits in data, such as in low-level programming, embedded systems, optimization, or solving algorithmic problems. These operators work directly on the binary representation of integers. Here’s how to use them effectively.
Understanding the bitwise operators
C++ provides six main bitwise operators:
- & (AND) – Returns 1 if both bits are 1.
- | (OR) – Returns 1 if at least one bit is 1.
- ^ (XOR) – Returns 1 if the bits are different.
- ~ (NOT) – Inverts all bits (1 becomes 0, 0 becomes 1).
- << (Left shift) – Shifts bits to the left, multiplying by powers of 2.
- >> (Right shift) – Shifts bits to the right, dividing by powers of 2 (arithmetic shift for signed, logical for unsigned).
These operators work on integral types (int, char, long, etc.) and are evaluated bit by bit.
For example:
unsigned char a = 5; // 00000101 unsigned char b = 3; // 00000011 cout << (a & b) << endl; // 1 → 00000001 cout << (a | b) << endl; // 7 → 00000111 cout << (a ^ b) << endl; // 6 → 00000110 cout << (~a) << endl; // 250 (assuming 8-bit) → 11111010 cout << (a << 1) << endl; // 10 → 00001010 (5 * 2) cout << (a >> 1) << endl; // 2 → 00000010 (5 / 2)
Common use cases and techniques
1. Checking if a number is odd or even
Use the AND operator with 1 to check the least significant bit (LSB).
if (n & 1) { cout << "Odd" << endl; } else { cout << "Even" << endl; }
2. Toggling a specific bit
Use XOR to flip a bit at a given position.
n ^= (1 << k); // Toggles the k-th bit (0-indexed)
3. Setting or clearing a bit
- Set the k-th bit:
n |= (1 << k)
- Clear the k-th bit:
n &= ~(1 << k)
This is useful in flags or configuration registers.
4. Extracting a bit
Check if the k-th bit is set:
bool isSet = (n >> k) & 1;
5. Swapping two numbers without extra space
Though not always recommended due to readability, XOR can swap values:
a ^= b; b ^= a; a ^= b;
Or more concisely:
a ^= b ^= a ^= b; // Be cautious with side effects and sequence points
6. Counting set bits (population count)
Manually loop through bits:
int count = 0; while (n) { count += n & 1; n >>= 1; }
Or use built-in functions like __builtin_popcount(n)
in GCC.
Important considerations
- Signed vs unsigned: Right shifting signed negative numbers is implementation-defined (usually arithmetic shift). Use unsigned types for predictable behavior.
- Integer promotion: Smaller types (like char, short) are promoted to int during operations. Be aware of sign extension.
- Operator precedence: Bitwise operators have lower precedence than comparison and arithmetic operators. Use parentheses to avoid bugs.
if ((flags & MASK) == VALUE) // Correct if (flags & MASK == VALUE) // Wrong! == has higher precedence
- Avoid undefined behavior: Shifting by negative counts or by more than the bit width is undefined.
x << n; // Undefined if n < 0 or n >= bit-width of x
Practical example: Managing flags
Bitwise operators are great for managing multiple boolean options in a single variable.
const int READ = 1 << 0; // 1 const int WRITE = 1 << 1; // 2 const int EXECUTE = 1 << 2; // 4 int permissions = 0; permissions |= READ | WRITE; // Grant read and write if (permissions & EXECUTE) { // Check execute cout << "Executable" << endl; } permissions &= ~WRITE; // Remove write
This pattern is widely used in system programming and APIs.
Basically, bitwise operators give you fine control over data at the bit level. They’re fast, efficient, and once you get used to binary thinking, quite intuitive. Just remember to use parentheses, prefer unsigned types, and document your bit logic clearly.
以上がcのビットワイズ演算子との作業方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undress AI Tool
脱衣画像を無料で

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ディレクトリ簡潔な(証明)簡潔(証明)は何ですか?どのベンチャーキャピタルが簡潔(証明)をサポートしていますか? SP1ZKVMとProver Network Opsuccccinctテクノロジークロスチェーン検証を証明するトークン経済学トークンの詳細トークンアラケーション潜在的トークンホルダーは、トークンの価格予測を証明するトークンの価格予測を証明するトークンの価格の予測を証明するトークンの潜在的なトークンの予測されるトークンの価格の予測を証明します。サクサク

ディレクトリ簡潔(証明)は、どのベンチャーキャピタルが簡潔(証明)をサポートしていますか?作業原則SP1ZKVMおよびProver Network Opsucccinctテクノロジークロスチェーン検証がトークン経済学トークンの詳細を証明するために、どのように簡潔(証明する)作業原則2025、2026、2027-2030簡潔な(証明)価格予測(証明)価格予測簡潔(証明)

ソフトウェアまたはゲームを開くと、「アプリケーションが正常に開始できない(0xc0000906)」が表示され、多くのユーザーが混乱し、どこから始めればよいかわからないというプロンプトが突然表示されます。実際、これらのエラーのほとんどは、システムファイルの破損またはランタイムライブラリの欠落によって引き起こされます。急いでシステムを再インストールしないでください。この記事では、いくつかのシンプルで効果的なソリューションを提供して、プログラムを迅速に復元するのに役立ちます。 1. 0xc0000906のエラーは何ですか?エラーコード0xc0000906は、Windowsシステムの一般的な起動例の例外です。これは通常、プログラムが実行中に必要なシステムコンポーネントや実行環境をロードできないことを意味します。この問題は、大規模なソフトウェアやゲームを実行するときに発生することがよくあります。主な理由には、必要なランタイムライブラリがインストールまたは破損していないことが含まれます。ソフトウェアインストールパッケージは無限です

STD :: IFSTREAMのSEEKGおよびTELLGメソッドを使用して、プラットフォーム間でファイルサイズを取得します。バイナリファイルを開き、最後まで配置することにより、tellg()を使用してバイト数を返します。 2。std :: filesystem :: file_sizeを使用することをお勧めします。コードは簡潔で、エラーは例外を介して処理されます。 C 17標準を有効にする必要があります。 3。POSIXシステムでは、STAT()関数を使用して、パフォーマンスに敏感なシナリオに適したファイルサイズを効率的に取得できます。適切な方法はコンパイラとプラットフォームに基づいて選択する必要があり、STD ::ファイルシステムを最初に使用する必要があります(利用可能な場合)。

Memory_order_relaxedは、カウンター、統計などの同期や順序保証なしでアトミティのみが必要なシナリオに適しています。1。メモリ_order_relaxedを使用する場合、操作はコンパイラまたはCPUが操作を再配置することができます。 2。例では、複数のスレッドがアトミックカウンターを増加させます。最終的な値のみを気にかけており、操作が一貫しているため、リラックスしたメモリ順序は安全で効率的です。 3. FETCH_ADDとLOADは、リラックスした場合に同期または順次制約を提供しません。 4。エラーの例では、プロデューサーと消費者の同期は、リラックスしたものを使用して実装されます。これにより、注文保証がないため、消費者が未給のデータ値を読み取る可能性があります。 5。正しい方法は

コンピューターは「MSVCP71.DLLがコンピューターから欠落している」とプロンプトします。これは通常、システムに重要な実行コンポーネントがないため、ソフトウェアが正常にロードされないためです。この記事では、ファイルの機能とエラーの根本原因を深く分析し、3つの効率的なソリューションを提供して、プログラムを迅速に実行するのに役立ちます。 1。MSVCP71.dllとは何ですか? MSVCP71.DLLは、Microsoft VisualC 2003のコアランタイムライブラリファイルに属し、Dynamic Link Library(DLL)タイプに属します。これは、主に標準関数、STLテンプレート、および基本的なデータ処理モジュールを呼び出すためにCで記述されたプログラムをサポートするために使用されます。 2000年代初頭に開発された多くのアプリケーションとクラシックゲームは、このファイルに依存して実行されます。ファイルが欠落または破損したら、

Cでのオペレーターの過負荷により、標準演算子の新しい動作をカスタムタイプに割り当てることができます。1。メンバー関数の過負荷を介して新しいオブジェクトを返します。 2。オーバーロード=現在のオブジェクトを変更し、参照を返します。 3。フレンド関数のオーバーロード

Cで正規表現を使用するには、ヘッダーファイルを含めて、パターンマッチングとテキスト処理に提供する機能を使用する必要があります。 1。STD:: regex_matchを使用して完全な文字列に一致し、文字列全体がパターンに準拠している場合にのみtrueを返します。 2。STD:: regex_searchを使用して、文字列の任意の位置で一致を見つけます。 3。STD:: SMATCHを使用してキャプチャグループを抽出し、マッチ[0]、マッチ[1]、およびその後のサブマッチを介して完全な一致を取得します。 4。STD:: regex_replaceを使用して一致するテキストを置き換え、1ドルや2ドルなどの参照でキャプチャグループをサポートします。 5.正規表現を構築するときにISETを追加できます(
