Tuesday, April 8, 2014

Turning On/Off/Flipping specific Bits in a Value

Here is a nice set of functions to do your bit manipulation in C#:


http://codeidol.com/community/dotnet/turning-bits-on-or-off/8901/



Here they are in VB.NET:

Public Function TurnBitOn(value As Integer, bitToTurnOn As Integer) As Integer Return (value Or bitToTurnOn)
End Function


Public Function TurnBitOff(value As Integer, bitToTurnOff As Integer) As Integer Return (value And Not bitToTurnOff)

End Function




Public Function FlipBit(value As Integer, bitToFlip As Integer) As Integer Return (value Xor bitToFlip)
End Function




Public Function TurnBitPositionOn(value As Integer, bitPosition As Integer) As Integer Return (value Or (1 << bitPosition))
End Function




Public Function TurnBitPositionOff(value As Integer, bitPosition As Integer) As Integer Return (value And Not (1 << bitPosition))
End Function




Public Function FlipBitPosition(value As Integer, bitPosition As Integer) As Integer Return (value Xor (1 << bitPosition))
End Function

No comments: