C/C++ Algorithms

Bit Manipulation

Bit masks कई boolean options unsigned integer में compact रखते हैं।

Bit Manipulation क्या है?

Bit masks कई boolean options unsigned integer में compact रखते हैं।

Flags set, clear, toggle और test करें।

महत्वपूर्ण बातें

  • Empty, single, duplicate और sorted input test करें।
  • Correctness और optimization अलग रखें।
  • Production में standard library को प्राथमिकता दें।

C और C++ code examples

C
कोड चलाएँ →
main.c
#include <stdio.h>

int main(void) {
    unsigned flags = 0;
    flags |= 1u << 1;
    flags |= 1u << 3;
    flags ^= 1u << 1;
    printf("flags=%u bit3=%u\n", flags, (flags >> 3) & 1u);
}
अपेक्षित output
flags=8 bit3=1
C++
कोड चलाएँ →
main.cpp
#include <bitset>
#include <iostream>

int main() {
    std::bitset<4> flags;
    flags.set(1);
    flags.set(3);
    flags.flip(1);
    std::cout << "flags=" << flags
              << " bit3=" << flags.test(3) << '\n';
}
अपेक्षित output
flags=1000 bit3=1

C और C++ की तुलना

Predictable shifts के लिए unsigned उपयोग करें। C masks और C++ bitset named operations तथा binary output देता है।

C

Loops, pointers, lengths और buffers स्पष्ट लिखे जाते हैं।

C++

Iterators और algorithms operation को storage से अलग करते हैं।

अभ्यास

दोनों versions चलाकर बदलें और language guarantees की तुलना करें।

  • हर comparison trace करें।
  • Duplicates और extreme values test करें।
  • Standard library के विरुद्ध benchmark करें।