0

I have some source code in my project where a num was set with some valid bit. I have one scenario where I need to reset one bit but does not able to implement the logic. Please help me to fix this code. Here is what I tried : https://ide.geeksforgeeks.org/online-cpp-compiler/1f2743ff-cdd3-449a-91af-92db72b9b2a0

enum myList
 {
     RL_A = 0x4000,
     RL_B = 0x8000
 };

int main() {
    
    uint16_t num;
    
    // Setting the bit 
    num |= RL_A;
    num |= RL_B;
    cout << std::hex << num << "\n";  // num = c000
    
    // Reset the bit RL_B
    num |= ~RL_B;  // Fix me !!
    cout << std::hex << num << "\n";  // num = ffff?

    return 0;
}

Could you please suggest how to reset RL_B in above num? Please fix the code : num |= ~RL_B; // Fix me !! Thanks!

Lundin
  • 195,001
  • 40
  • 254
  • 396
Ratnesh
  • 298
  • 3
  • 14
  • 5
    `num |= ~RL_B;` -> `num &= ~RL_B;`. Take a pencil and a piece of paper and do the math, you'll understand – Jabberwocky Feb 14 '23 at 12:05
  • 2
    In case you are learning from geeksforgeeks or other such online sources of diverse quality, maybe just read a book instead? Any decent C or C++ book will address the bitwise operators. – Lundin Feb 14 '23 at 12:06
  • BTW: you never initialize `num`. So the outcome of your program is undefined. Most likely the initial value of `num` is undetermined. – Jabberwocky Feb 14 '23 at 12:10
  • Ratnesh, Good first step: Initialize `num` with `uint16_t num = 0;` – chux - Reinstate Monica Feb 14 '23 at 12:10
  • If you already **know** the bit is set, you can clear it with `num ^= RL_B;` – Eljay Feb 14 '23 at 12:52

0 Answers0