
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Turning Bits On or Off
|
123
public static int TurnBitOn(int value, int bitToTurnOn)
{
return (value | bitToTurnOn);
}
The following method turns one or more bits off using a bit flag passed in to the
bitToTurnOff parameter:
public static int TurnBitOff(int value, int bitToTurnOff)
{
return (value & ~bitToTurnOff);
}
The following method flips a bit to its opposite value using a bit flag passed in to the
bitToFlip parameter:
public static int FlipBit(int value, int bitToFlip)
{
return (value ^ bitToFlip);
}
The following method turns one or more bits on using a numeric bit position value
passed in to the
bitPosition parameter:
public static int TurnBitPositionOn(int value, int bitPosition)
{
return (value | (1 << bitPosition));
}
The following method turns one or more bits off using a numeric bit position value
passed in to the
bitPosition parameter:
public static int TurnBitPositionOff(int value, int bitPosition)
{
return (value & ~(1 << bitPosition));
}
The following method flips a bit to its opposite value using a numeric bit position
value passed in to the
bitPosition parameter:
public static int FlipBitPosition(int value, int bitPosition)
{
return (value ^ (1 << bitPosition));
}
Discussion
When a large number of flags are required, and particularly when combinations of
flags can be set, it becomes ...