Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder Apothem's Avatar
    Join Date
    Mar 2008
    Posts
    380
    Thanks
    36
    Thanked 25 Times in 25 Posts

    C/C++: Bit setting procedure?

    How would you go about setting a bit in an integer variable WITHOUT the introduction of variables/loops/branches/etc.

    i.e. let's have something like:
    Code:
    // num = num to set; any 32 bit int
    // bit = 1 or 0
    // pos = 0 <= pos <= 31
    // Assume Little Endian & ints are 32 bits and that right bit shift is logical (not arithmetic).
    int bit_set(int num, int bit, int pos) {
      // some code here
      return num;
    }
    What can be done to set the num's bit at pos to bit, such that no extra variable, any branches (which encases loops), or structs/objects are introduced? In other words, bit setting with just plain operators. I can't really figure this out; I can think of how to do it by introducing one extra variable or branches, but not of a way without them.
    Last edited by Apothem; 11-16-2011 at 05:29 AM.

  • #2
    Senior Coder
    Join Date
    Aug 2006
    Posts
    1,235
    Thanks
    10
    Thanked 270 Times in 269 Posts
    I may be missing something about the requirement, but wouldn't you just do:
    Code:
    num |= bit<<pos;
    Dave

  • #3
    Regular Coder Apothem's Avatar
    Join Date
    Mar 2008
    Posts
    380
    Thanks
    36
    Thanked 25 Times in 25 Posts
    The problem is that what if the bit at that pos is 1 but you want to set it to 0? The or operator would make no difference.

    I think I found the solution looking around a bit more:
    1. Set the bit to 0
    2. Set the bit to <bit>

    i.e:
    num = num & ~(1<<pos);
    num = num | (bit << pos);

  • #4
    Senior Coder
    Join Date
    Aug 2006
    Posts
    1,235
    Thanks
    10
    Thanked 270 Times in 269 Posts
    Ah yes, you're right!
    Dave


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •