How do you randomly zero a bit in an integer?

后端 未结 13 1901
無奈伤痛
無奈伤痛 2021-02-05 10:11

Updated with newer answer and better test

Let\'s say I have the number 382 which is 101111110.

How could I randomly turn a bit which is not 0 to

13条回答
  •  温柔的废话
    2021-02-05 10:53

    Ok, a lot of wrong answers. Here's one that works:

    1. determine which bit to flip. Do this randomly. I won't supply the code, it's pretty straightforward.
    2. setup a bitmask with all zeros, with a 1 for the bit in question. So for example, if it's the 3rd bit, your bitmask might be 00000100. Again, this doesn't require code.
    3. bitwise XOR your number with the bit mask. If you're unfamiliar with the operator it's the hat operator: ^

    Here's some sample code:

    int myInt; // set this up with your original value
    int myBitmask; // set this up with the bit mask via steps 1 and 2.
    int randomlyZeroedBitInt = myInt ^ myBitmask;
    

    Edit: On a fifth read of the question, I have a question in return: you are wanting to do which of the following:

    1. Randomly zero a bit, but only if that bit is already 1. In other words, if the bit in question isn't already 1, the operation is a no-op.
    2. Randomly choose a bit that is 1 and zero it. This operation always chooses a bit that is already 1 and always zeros it. The operation is only a no-op if the original value is 0.

    Edit 2:

    2 is correct,(15chars) – Fredou

    In that case, my general algorithm stands; merely choose the bit in step 1 with internal logic. Alternatively, choose a fully random bit in step 1 and repeat until the value of myInt and randomlyZeroedBitInt are not equal.

    Unfortunately either case means a more complex algorithm, as you'll either need to iterate over every bit in your value to determine which to flip, or you'll need to loop the algorithm until a bit is flipped.

提交回复
热议问题