Search code examples
c#genetic-algorithmmutation

BitArray change bit within range


How can I ensure that when changing a bit from a BitArray, the BitArray value remains in a range.

Example:

Given the range [-5.12, 5.12] and

a = 0100000000000000011000100100110111010010111100011010100111111100 ( = 2.048)

By changing a bit at a random position, I need to ensure that the new value remains in the given range.


Solution

  • I'm not 100% sure what you are doing and this answer assumes you are storing a as a 64-bit value (long) currently. The following code may help point you in the right direction.

    const double minValue = -5.12;
    const double maxValue = 5.12;
    
    var initialValue = Convert.ToInt64("100000000000000011000100100110111010010111100011010100111111100", 2);
    var changedValue = ChangeRandomBit(initialValue); // However you're doing this
    
    var changedValueAsDouble = BitConverter.Int64BitsToDouble(initialValue);
    if ((changedValueAsDouble < minValue) || (changedValueAsDouble > maxValue))
    {
        // Do something
    }